您的位置:首页 > 其它

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

2017-01-09 20:57 411 查看
今天在使用URLWithString拼接NSURL的时候出现了nil:

[objc] view
plain copy

 print?





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尽量这样用:

[objc] view
plain copy

 print?





// 这样用,就不容易出现像上面的问题  

        NSString *urlStr = [NSString stringWithFormat:@"%@%@?%@", host_url, baseurl, postURL];  

        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  

        NSURL *url = [NSURL URLWithString:urlStr];  

这样就不容易出现URLWithString拼接NSURL为nil的情况,至少我这里就不会出现了。。

转载自:http://blog.csdn.net/zengraoli/article/details/16878393
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: