4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSURLComponentsのエンコードが期待していたものと違っていた

Last updated at Posted at 2016-01-27

環境

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

ドキュメントにあったすべての文字がエンコードされていないようでした。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?