NSData& NSURL - 空间有问题的网址

时间:2009-09-17 20:19:28

标签: iphone xcode 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中。

3 个答案:

答案 0 :(得分:98)

使用: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'  

答案 1 :(得分:12)

swift 3.0方法(现在不推荐使用stringByAddingPercentEscapesUsingEncoding和stringByAddingPercentEncodingWithAllowedCharacters):

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

答案 2 :(得分:2)

在iOS 9.0中已弃用

stringByAddingPercentEscapesUsingEncoding,建议您改用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);