为什么我的NSURL对象等于nil?我的道路是正确的

时间:2011-06-28 10:51:55

标签: iphone 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];
NSLog(@"urlString: %@", urlString); 
NSURL *urlFromURLString = [NSURL URLWithString:urlString];

我的日志是:http://maps.google.com/maps/geo?q=53.872874,27.527790&output=csv&sensor=false&key=swizzlec hops

我可以将此网址复制并粘贴到浏览器并确定,但是urlFromURLString = nil。但是,为什么?

3 个答案:

答案 0 :(得分:3)

尝试

 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];

我认为您的网址不能包含空格

答案 1 :(得分:3)

我相信你需要使用

stringByAddingPercentEscapesUsingEncoding:
在将urlString传递给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 :(得分:0)

这是一种更好的方法:

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