文字列をURLエンコードするにはどうすればいいですか?質問する

文字列をURLエンコードするにはどうすればいいですか?質問する

NSStringスペースと文字を含むURL 文字列 ( ) があります。文字列全体 (アンパサンド文字とスペースを含む)&を URL エンコードするにはどうすればよいですか?&

ベストアンサー1

残念ながら、stringByAddingPercentEscapesUsingEncoding常に100%動作するわけではありません。URL以外の文字はエンコードされますが、予約文字(スラッシュ/やアンパサンドなど&)はそのまま残ります。どうやらこれはバグApple も認識していますが、まだ修正されていないため、私はこのカテゴリを使用して文字列を URL エンコードしています。

@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;
}

次のように使用します:

NSString *urlEncodedString = [@"SOME_URL_GOES_HERE" urlencode];

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

これも機能します:

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

このテーマに関する良い読み物:

Objective-c iPhone で文字列をパーセントエンコードしますか?
Objective-C および Swift URL エンコーディング

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/

おすすめ記事