@blog.justoneplanet.info

日々勉強

Objective-CでURLエンコードする

■実装

Util.h

#import <Foundation/Foundation.h>
@interface Util : NSObject {
}
+ (NSString *)urlencode:(NSString *)text;
+ (NSString *)urldecode:(NSString *)text;
@end

Util.m

#import "Util.h"
@implementation Util
//encode
+ (NSString *)urlencode:(NSString *)text
{
    CFStringRef strRef = CFURLCreateStringByAddingPercentEscapes(
        NULL,
        (CFStringRef)text,
        NULL,
        (CFStringRef)@"!*'();:@&=+$,/?%#[]~",
        kCFStringEncodingUTF8);
    NSString * str = [NSString stringWithString:(NSString *)strRef];
    CFRelease(strRef);
    return str;
}

// decode
+ (NSString *)urldecode:(NSString *)text
{
    CFStringRef strRef = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
        NULL,
        (CFStringRef) text,
        CFSTR(""),
        kCFStringEncodingUTF8);
    NSString * str = [NSString stringWithString:(NSString *)strRef];
    CFRelease(strRef);
    return str;
}
@end

■テスト

ちゃんと書いておく。

UtilTest.h

#import <GHUnitIOS/GHUnit.h>
@interface UtilTest : GHTestCase {    
}
@end

UtilTest.m

#import "UtilTest.h"
#import "Util.h"
@implementation UtilTest
- (void)test_urlencode
{
    NSString *url1 = [NSString stringWithString:@"%E3%83%86%E3%82%B9%E3%83%88%E3%82%B1%E3%83%BC%E3%82%B9"];
    NSString *url2 = [NSString stringWithString:[Util urlencode:@"テストケース"]];
    GHAssertEqualObjects(url1, url2, @"match!");
    
    NSString *url3 = [NSString stringWithString:@"%E9%9A%A3%E4%BA%BA%E3%81%AF%E7%BE%8E%E4%BA%BA"];
    NSString *url4 = [NSString stringWithString:[Util urlencode:@"隣人は美人"]];
    GHAssertEqualObjects(url3, url4, @"match!");
    
    // 記号などはしっかりテストしましょう
    NSString *url5 = [NSString stringWithString:@"%21%22%23%24%25%26%27%28%290%3D%7E%7C%60%7B%7D%2A%2B%3C%3E%3F_"];
    NSString *url6 = [NSString stringWithString:[Util urlencode:@"!\"#$%&'()0=~|`{}*+<>?_"]];
    GHAssertEqualObjects(url5, url6, @"match!");
}

- (void)test_urldecode
{
    NSString *url1 = [NSString stringWithString:[Util urldecode:@"%E3%83%86%E3%82%B9%E3%83%88%E3%82%B1%E3%83%BC%E3%82%B9"]];
    NSString *url2 = [NSString stringWithString:@"テストケース"];
    GHAssertEqualObjects(url1, url2, @"match!");
    
    NSString *url3 = [NSString stringWithString:[Util urldecode:@"%E9%9A%A3%E4%BA%BA%E3%81%AF%E7%BE%8E%E4%BA%BA"]];
    NSString *url4 = [NSString stringWithString:@"隣人は美人"];
    GHAssertEqualObjects(url3, url4, @"match!");
    
    // 記号などはしっかりテストしましょう
    NSString *url5 = [NSString stringWithString:[Util urldecode:@"%21%22%23%24%25%26%27%28%290%3D%7E%7C%60%7B%7D%2A%2B%3C%3E%3F_"]];
    NSString *url6 = [NSString stringWithString:@"!\"#$%&'()0=~|`{}*+<>?_"];
    GHAssertEqualObjects(url5, url6, @"match!");
}
@end

つーかNSURLとかを拡張したほうが良かったかな。

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment