NSData&NSURL – 与空间有问题的url

我在我的应用程序中有以下代码。

NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:pathOfThumbNail]]; 

pathOfThumbNail有以下path


http://70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg


当我在Safari浏览器中打开上面的path时,path会自动更改,并且图像显示成功。

http://70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg


但在iPhone中,由于path空间的原因,图像不会在nsdata中加载。

使用:stringByAddingPercentEscapesUsingEncoding:

使用给定编码返回接收方的表示forms,以确定将接收方转换为合法URLstring所需的百分比转义。

 -(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding 

使用编码来确定将接收方转换为合法URLstring所需的百分比转义的接收方表示。 如果编码无法编码特定字符,则返回nil

@rule每个请求添加

 NSString* urlText = @"70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg"; NSString* urlTextEscaped = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString: urlTextEscaped]; NSLog(@"urlText: '%@'", urlText); NSLog(@"urlTextEscaped: '%@'", urlTextEscaped); NSLog(@"url: '%@'", url); 

NSLog输出:

 urlText:'70 .84.58.40 / projects / igolf / TipThumb / GOLF 58B.jpg'  
 urlTextEscaped:'70 .84.58.40 / projects / igolf / TipThumb / GOLF%2058B.jpg'  
 url:'70 .84.58.40 / projects / igolf / TipThumb / GOLF%2058B.jpg'  

一个迅速3.0的方法(stringByAddingPercentEscapesUsingEncoding和stringByAddingPercentEncodingWithAllowedCharacters现在似乎已被弃用):

 let urlString ="your/url/".addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) 

stringByAddingPercentEscapesUsingEncoding已经在iOS 9.0中被弃用了,build议你改用stringByAddingPercentEncodingWithAllowedCharacters

这里是iOS 9.0的Objective-C代码

 NSString* urlText = @"70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg"; NSString* urlTextEscaped = [urlText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSURL *url = [NSURL URLWithString: urlTextEscaped]; enter code here NSLog(@"urlText: '%@'", urlText); NSLog(@"urlTextEscaped: '%@'", urlTextEscaped); NSLog(@"url: '%@'", url);