Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

環境

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

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away