2009-11-17 56 views
10

如何在NSURL中進行URL編碼?在ObjC中的NSURL編碼

感謝

+0

現在更容易與iOS 7:http://stackoverflow.com/questions/3423545/objective-c-iphone-percent-encode-a-string/20271177 #20271177 – 2015-11-04 16:58:24

回答

27

您可以使用stringByAddingPercentEscapesUsingEncoding:

NSString* escapedUrlString = 
    [unescapedString stringByAddingPercentEscapesUsingEncoding: 
         NSUTF8StringEncoding]; 

但是,以我的經驗,這種方法還不太完善(在處理某些保留字符),而且在許多情況下,我需要使用變體:

NSString * escapedUrlString = 
    (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL, 
    (CFStringRef)unescapedString, 
    NULL, 
    (CFStringRef)@"!*'();:@&=+$,/?%#[]", 
    kCFStringEncodingUTF8); 
+3

+1,但是提醒你'CFURLCreateStringByAddingPercentEscapes'返回一個帶有+1保留計數的字符串,所以你必須在你完成時釋放它。 – 2009-11-17 15:12:49

+0

你救了我一天@notnoop – 2015-07-29 06:32:28

3

這爲我工作:

NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:STRING_ENCODING_IN_THE_SERVER]] 
                 encoding:STRING_ENCODING_IN_THE_SERVER 
                 error:&error];