How do I URL encode a string

前端 未结 22 1703
轮回少年
轮回少年 2020-11-22 07:16

I have a URL string (NSString) with spaces and & characters. How do I url encode the entire string (including the & ampersand

22条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 08:13

    New APIs have been added since the answer was selected; You can now use NSURLUtilities. Since different parts of URLs allow different characters, use the applicable character set. The following example encodes for inclusion in the query string:

    encodedString = [myString stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
    

    To specifically convert '&', you'll need to remove it from the url query set or use a different set, as '&' is allowed in a URL query:

    NSMutableCharacterSet *chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
    [chars removeCharactersInRange:NSMakeRange('&', 1)]; // %26
    encodedString = [myString stringByAddingPercentEncodingWithAllowedCharacters:chars];
    

提交回复
热议问题