How do I URL encode a string

前端 未结 22 1682
轮回少年
轮回少年 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:15

    Unfortunately, stringByAddingPercentEscapesUsingEncoding doesn't always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash / and ampersand &) alone. Apparently this is a bug that Apple is aware of, but since they have not fixed it yet, I have been using this category to url-encode a string:

    @implementation NSString (NSString_Extended)
    
    - (NSString *)urlencode {
        NSMutableString *output = [NSMutableString string];
        const unsigned char *source = (const unsigned char *)[self UTF8String];
        int sourceLen = strlen((const char *)source);
        for (int i = 0; i < sourceLen; ++i) {
            const unsigned char thisChar = source[i];
            if (thisChar == ' '){
                [output appendString:@"+"];
            } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 
                       (thisChar >= 'a' && thisChar <= 'z') ||
                       (thisChar >= 'A' && thisChar <= 'Z') ||
                       (thisChar >= '0' && thisChar <= '9')) {
                [output appendFormat:@"%c", thisChar];
            } else {
                [output appendFormat:@"%%%02X", thisChar];
            }
        }
        return output;
    }
    

    Used like this:

    NSString *urlEncodedString = [@"SOME_URL_GOES_HERE" urlencode];
    
    // Or, with an already existing string:
    NSString *someUrlString = @"someURL";
    NSString *encodedUrlStr = [someUrlString urlencode];
    

    This also works:

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

    Some good reading about the subject:

    Objective-c iPhone percent encode a string?
    Objective-C and Swift URL encoding

    http://cybersam.com/programming/proper-url-percent-encoding-in-ios
    https://devforums.apple.com/message/15674#15674 http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/

    0 讨论(0)
  • 2020-11-22 08:15

    This code helped me for encoding special characters

    NSString* encPassword = [password stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    
    0 讨论(0)
  • 2020-11-22 08:16

    ios 7 update

    NSString *encode = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSString *decode = [encode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    0 讨论(0)
  • 2020-11-22 08:18

    Apple's advice, in the 10.11 release notes, is:

    If you need to percent-encode an entire URL string, you can use this code to encode a NSString intended to be a URL (in urlStringToEncode):

    NSString *percentEncodedURLString =
      [[NSURL URLWithDataRepresentation:[urlStringToEncode dataUsingEncoding:NSUTF8StringEncoding] relativeToURL:nil] relativeString];
    
    0 讨论(0)
提交回复
热议问题