如何处理带有空格的URL?

时间:2021-08-05 16:48:49
NSString * urlCached = URL.CacheImageURL;NSURL * url = [NSURL URLWithString:urlCached];NSData * data=[NSData dataWithContentsOfURL:url];

It works fine for most URL. However, if URL contains space such as http://google.com/Hello World.htm then it won't work.

它适用于大多数URL。但是,如果网址包含http://google.com/Hello World.htm等空格,则无法使用。

What should I do for such URLs?

我该怎么做这些网址?

2 个解决方案

#1


You can percent-escape characters which aren't valid inside an URL:

您可以在URL中转义无效的转义字符:

NSURL *url = [NSURL URLWithString:    [urlCached stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

This is easy but not always correct; for escaping valid URL special chars (%, &, ?, :)as well, use the CFURLCreateStringByAddingPercentEscapes() function.

这很容易,但并不总是正确的;要转义有效的URL特殊字符(%,&,?,:),请使用CFURLCreateStringByAddingPercentEscapes()函数。

#2


Encode the URL... use %20 instead of the space. For reference: http://www.w3schools.com/tags/ref_urlencode.asp

编码URL ...使用%20而不是空格。供参考:http://www.w3schools.com/tags/ref_urlencode.asp

#1


You can percent-escape characters which aren't valid inside an URL:

您可以在URL中转义无效的转义字符:

NSURL *url = [NSURL URLWithString:    [urlCached stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

This is easy but not always correct; for escaping valid URL special chars (%, &, ?, :)as well, use the CFURLCreateStringByAddingPercentEscapes() function.

这很容易,但并不总是正确的;要转义有效的URL特殊字符(%,&,?,:),请使用CFURLCreateStringByAddingPercentEscapes()函数。

#2


Encode the URL... use %20 instead of the space. For reference: http://www.w3schools.com/tags/ref_urlencode.asp

编码URL ...使用%20而不是空格。供参考:http://www.w3schools.com/tags/ref_urlencode.asp