您的位置:首页 > 其它

直接用URLWithString来拼接NSURL有时候得到的NSURL是为nil的

2015-01-07 13:27 471 查看
今天在使用URLWithString拼接NSURL的时候出现了nil:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?%@",host_url,baseurl,postURL]];


查了一下原因:

This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.

大概的意思是说,转义方面的,但并非我这里拼接为nil的原因。不过他给的解决方案缺让我最终拼接的NSURL不为nil了。。

所以以后在使用URLWithString来拼接NSURL尽量这样用:
// 这样用,就不容易出现像上面的问题
NSString *urlStr = [NSString stringWithFormat:@"%@%@?%@", host_url, baseurl, postURL];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];


这样就不容易出现URLWithString拼接NSURL为nil的情况,至少我这里就不会出现了。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: