问题
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