Why does my NSURL object is equal to nil? My path is correct

▼魔方 西西 提交于 2020-01-03 05:45:06

问题


NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%lf,%lf&output=csv&sensor=false&key=swizzlec hops", coordinate.latitude,coordinate.longitude];
NSLog(@"urlString: %@", urlString); 
NSURL *urlFromURLString = [NSURL URLWithString:urlString];

My log is : http://maps.google.com/maps/geo?q=53.872874,27.527790&output=csv&sensor=false&key=swizzlec hops

I can copy this url and paste to the browser and its ok, but urlFromURLString = nil. But, why?


回答1:


I believe you need to use

stringByAddingPercentEscapesUsingEncoding:

on urlString before passing it to NSURL.

NSString *urlString = [[NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%lf,%lf&output=csv&sensor=false&key=swizzlec hops", coordinate.latitude,coordinate.longitude] stringByAddingPercentEscapesUsingEncoding::NSUTF8StringEncoding];



回答2:


Try

 NSString *urlString = [[NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%lf,%lf&output=csv&sensor=false&key=swizzlec hops", coordinate.latitude,coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

I don't think you can have spaces in your URL




回答3:


This is a better approach:

NSString* escapedUrl = [originalUrl   stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *urlFromURLString = [NSURL URLWithString:escapedUrl];


来源:https://stackoverflow.com/questions/6505294/why-does-my-nsurl-object-is-equal-to-nil-my-path-is-correct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!