Objective-C URL编码问题

时间:2015-05-12 13:35:12

标签: objective-c

我正在创建一个类似的URL字符串:

[Items appendString:[object objectForKey:@"Items"]];
[Items appendString:@"*"];
[Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)];
//This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/FLATWORK SUPPLY & INSTALL - 75% of CONTRACT*SUMP PUMP PIT

//add Items to URL
NSString *fullURL = [NSString stringWithFormat:@"https://example.com?Items=%@, [Items stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

但它会像这样返回:

Items=~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2025%25%20of%20CONTRACT*~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2075%25%20of%20CONTRACT*SUMP%20PUMP%20PIT

如何让它像这样返回:

{p> %20%26%20而不是%20&%20的{​​{1}}?

3 个答案:

答案 0 :(得分:2)

我认为问题在于该方法试图过于聪明 - 它只能获得合法网址所需的数量,并且因为您的字符串中没有问号,它可能会认为它可以将&符号留在。

尝试构建整个URL并在整个URL上进行转义。

NSString *fullURL = [[@"https://example.com?Items=" stringByAppendingString: items]                       
                      stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

或者也许使用stringByAddingPercentEncodingWithAllowedCharacters:

答案 1 :(得分:0)

试试这个。

fullURL=[fullURL stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
NSLog(@"fullURL: %@ ...", fullURL);

答案 2 :(得分:0)

使用CFURLCreateStringByAddingPercentEscapes()获取字符的UTF8stringencoding

NSString *urlString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) Items, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8))