環境
Xcode 7.2
OS X 10.11.1
URLのパーセントエンコード
URL Session Programming Guide:Encoding URL Data
の中で、URLのエンコードはこう実装するといいよ、と書いてあった
CFStringRef originalString = ...
CFStringRef encodedString = CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
originalString,
NULL,
CFSTR(":/?#[]@!$&'()*+,;="),
kCFStringEncodingUTF8);
iOS8以降は、NSURLComponentsのqueryItemsを設定すると、
パーセントエンコードされた状態でクエリストリングが取得できると知った。
しかし、上記のドキュメントと同じようにエンコードされるわけではないらしく、ちょっとハマってました。。。
以下、expectaを使ったテストとその結果です。
- テストコード
it(@"should encode URL data", ^{
NSString *str = @":/?#[]@!$&'()*+,;=";
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost"];
components.queryItems = @[[NSURLQueryItem queryItemWithName:@"where" value:str]];
expect([components URL]).to.equal(@"http://localhost?%3a%2f%3f%23%5b%5d%40%21%24%26%27%28%29%2a%2b%2c%3b%3d");
});
- 結果
failed:
expected: http://localhost?where=%3a%2f%3f%23%5b%5d%40%21%24%26%27%28%29%2a%2b%2c%3b%3d,
got: http://localhost?where=:/?%23%5B%5D@!$%26'()*+,;%3D
ドキュメントにあったすべての文字がエンコードされていないようでした。