close

參考網頁:
https://madebymany.com/blog/url-encoding-an-nsstri...
http://stackoverflow.com/questions/25693758/ios-ns...
http://stackoverflow.com/questions/21829489/what-i...


起初,想把我程式內的URL改成percent encoding format。
例如:http://www.test.com/example?param=/wEF+rfc==
換成:http://www.test.com/example?param=%2FwEF%2Brfc%3D%3D


但使用了以下兩個functions得出來的結果都不是我要的。

stringByAddingPercentEscapesUsingEncoding
will convert the Unicode character to the percent escape format.

stringByReplacingPercentEscapesUsingEncoding 
will do the opposite, convert the percent escape to the Unicode.

原來這兩個functions遇到以下符號是不作用的。

! ' ( ) * + , / : ; = ? @ # $ & [ ]
%21 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %23 %24 %26 %5B %5D


Examples:

NSString *rawText = @"+886, Taipei, Taiwan";
NSString *encodedText = [rawText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Encoded text: %@", encodedText);
NSString *decodedText = [encodedText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Original text: %@", decodedText);

Here’s the output:

Encoded text: +886,%20Taipei,%20Taiwan
Original text: +886, Taipei, Taiwan


需要改成以下寫法:

- (NSString *)urlEncode:(NSString *)str {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)str, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
}

NSString *baseURL = @"http://www.test.com/example";
NSString *paramsString = @"/wEF+rfc==";
NSString *resultingURLString = [NSString stringWithFormat:@"%@?param=%@", baseURL, [self urlEncode:paramsString]];

Here’s the output:

http://www.test.com/example?param=%2FwEF%2Brfc%3D%...
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 viaLondon 的頭像
    viaLondon

    viaLondon的部落格

    viaLondon 發表在 痞客邦 留言(0) 人氣()