How do I URL encode a string

前端 未结 22 1954
轮回少年
轮回少年 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条回答
  •  Happy的楠姐
    2020-11-22 08:04

    After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.

    IF the target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:

    (Objective C code)

    @implementation NSString (NSString_urlencoding)
    
    - (NSString *)urlencode {
        static NSMutableCharacterSet *chars = nil;
        static dispatch_once_t pred;
    
        if (chars)
            return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
    
        // to be thread safe
        dispatch_once(&pred, ^{
            chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
            [chars removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
        });
        return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
    }
    @end
    

    This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:

    NSString *myusername = "I'm[evil]&want(to)break!!!$->àéìòù";
    NSLog(@"Source: %@ -> Dest: %@", myusername, [myusername urlencode]);
    

    That will print on your debug console:

    Source: I'm[evil]&want(to)break!!!$->àéìòù -> Dest: I%27m%5Bevil%5D%26want%28to%29break%21%21%21%24-%3E%C3%A0%C3%A9%C3%AC%C3%B2%C3%B9

    ... note also the use of dispatch_once to avoid multiple initializations in multithread environments.

提交回复
热议问题