NSData的&NSURL - 网址与具有空间的问题
题
我在我的申请下面的代码
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:pathOfThumbNail]];
pathOfThumbNail具有以下路径
http://70.84.58.40/projects/igolf/TipThumb/GOLF 58B .JPG
当我在上面Safari浏览器路径打开 - 路径被自动地改变与被成功地显示图像
http://70.84.58.40/projects/igolf/TipThumb/GOLF% 2058B.jpg
但是,在iPhone,由于在路空间,图像不会在NSData的加载。
解决方案
使用:stringByAddingPercentEscapesUsingEncoding:
返回使用给定的编码,以确定百分比的所述接收机的表示逸出必要给接收机转换为法定URL字符串。
-(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
使用编码来确定的百分比的接收器的一种表示逸出必要给接收机转换为法定URL字符串。返回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被弃用,建议您使用stringByAddingPercentEncodingWithAllowedCharacters
代替。
以下是适用于Objective-C代码>的iOS 9.0
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);
不隶属于 StackOverflow