URLWithString: returns nil

2019-01-10 13:51发布

it may be very easy, but I don't seems to find out why is URLWithString: returning nil here.

//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString* stringURL = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false&key=", webName];
NSURL* url = [NSURL URLWithString:stringURL];

7条回答
家丑人穷心不美
2楼-- · 2019-01-10 14:05

The URLWithString: call will return a nil if the string passed to it is malformed. Since NSURL returns nil for malformed urls, NSLog your string and set breakpoints to see exactly what is being passed to your NSURL creation method. If your URLWithString works with a hard coded value, that's further proof that whatever you are passing is malformed.see

查看更多
在下西门庆
3楼-- · 2019-01-10 14:12

Use This Function if you deal with file saved on file manager.

NSURL *_url = [NSURL fileURLWithPath:path];
查看更多
可以哭但决不认输i
4楼-- · 2019-01-10 14:13

I think your accented characters are throwing things off; they won't be handled by -stringByAddingPercentEscapesUsingEncoding:.

查看更多
Juvenile、少年°
5楼-- · 2019-01-10 14:14

I guess you need to use -[NSString stringByAddingPercentEscapesUsingEncoding:]. See Apple doc.

Another comment is that, as an old timer, I find it a bit uneasy to put non-ASCII characters in a source file. That said, this Apple doc says, starting from 10.4, UTF-16 strings are OK inside @"...". Somehow GCC seems to correctly convert the source file in Latin-1 into UTF-16 in the binary, but I think it's safest to use 7-bit ASCII characters only inside the source code, and use NSLocalizedString.

查看更多
做自己的国王
6楼-- · 2019-01-10 14:24

You can use NSURL directly without NSString.

//.h file

@interface NewsBrowser : UIViewController {

    UIWebView *webView;
    NSURL *NewsUrl;

}

@property (nonatomic, retain) IBOutlet UIWebView *webView;

@property(nonatomic,assign)NSURL *NewsUrl;

@end

//.m file

[webView loadRequest:[NSURLRequest requestWithURL:NewsUrl]];

And I pass the URL from another view (using NewsUrl variable) to this view.

Try it.

查看更多
Fickle 薄情
7楼-- · 2019-01-10 14:26

NSURL URLWithString:@"" will return nil if the URL does not conform to RFC 2396 and they must be escaped

If you read through rfc2396 in the link you will get loads of details

A great site I found for checking where the offending character is, choose the path option for URL

http://www.websitedev.de/temp/rfc2396-check.html.gz

查看更多
登录 后发表回答