NSMutableString *string = [[NSMutableString alloc]initWithString:
@"http%3A%2F%2Fsupport24hour.com%2Fworkplace2%2Fbuttler%2Fimage.php%3Fwidth%3D534%26height%3D256%26image%3Duploads%2Fdeals%2FdealImage%2Fdeal_1383005121_IGA+Logo.JPG"];
[string replaceOccurrencesOfString:@"+" withString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];
NSURL * url = [NSURL URLWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
答案 0 :(得分:1)
您不得对整个字符串进行百分比编码。相反,只有组件中的 data octet 必须可能被编码。
换句话说,URI由由某些字符分隔的组件和子组件组成。这些字符称为“保留字符”。不一定组件的分隔符肯定不包含在百分比编码中。
请注意,网址的每个组件可能需要稍微不同的百分比编码。
另见RFC 3986。
URL的一般结构如下:
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
以下两个示例直接从RFC中复制,显示其组成部分:
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose
“查询组件”包含一个“键/值”参数列表,其键和值之间用“=”分隔,其参数用“&”分隔。
查询组件是问号'?'
之后的所有内容,直到哈希字符'#'
。
以下代码对名称或参数的值进行编码。请注意,参数必须用'&'分隔,名称和值必须用'='分隔。
static NSString* form_urlencode_rfc3986(NSString* s) {
CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
//CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@~");
// Modified for urls (excluding '~'):
CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@");
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)s,
charactersToLeaveUnescaped,
legalURLCharactersToBeEscaped,
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
答案 1 :(得分:1)
我的一位同事遇到了同样的问题,请尝试下面的代码行。希望你的问题能得到解决
NSMutableString *string = [[NSMutableString alloc]initWithString:
@"http%3A%2F%2Fsupport24hour.com%2Fworkplace2%2Fbuttler%2Fimage.php%3Fwidth%3D534%26height%3D256%26image%3Duploads%2Fdeals%2FdealImage%2Fdeal_1383005121_IGA+Logo.JPG"];
string = [[NSMutableString alloc] initWithString:[[string stringByURLDecode] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSURL * url = [NSURL URLWithString:string];
NSLog(@"url = %@",url);
其中stringByURLDecode是用于解码URL的类别方法,它就像这样
- (NSString *)stringByURLDecode {
NSMutableString *tempStr = [NSMutableString stringWithString:self];
[tempStr replaceOccurrencesOfString:@"+" withString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
return [[NSString stringWithFormat:@"%@",tempStr] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
最好的运气(y)
答案 2 :(得分:0)
嗯...在将字符串转换为NSURL之前打印字符串怎么样?它看起来像你期待的那样吗?
另外:替换" +"有空格还是你真的想要删除它吗?