9/26/2011

短縮URLを作るNSString (shortURL) カテゴリ

昨日の短縮URLを展開するNSString (expandURL) カテゴリと対となるカテゴリ。
Bitly APIを使用しているので、事前にBitlyのアカウントとAPIキーを取得しておく必要がある。また、JSON形式の返り値をNSDictionaryに変換するためにSBJSONを使用している。


NSString+shortURL.h
#import <Foundation/NSString.h>

@interface NSString (shortURL)
+ (NSString *)shortURL:(NSString *)longUrl;
@end

NSString+shortURL.m
#import "NSString+shortURL.h"
#import "SBJson.h"

static NSString *kBitlyWrapperString = @"http://api.bit.ly/shorten?version=2.0.1&format=json&longUrl=";
static NSString *kBitlyFootterString = @"&login=ログイン名&apiKey=APIキー";

@implementation NSString (shortURL)

+ (NSString *)shortURL:(NSString *)longUrl{
NSString *aaa = nil;
NSString *escapeStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)longUrl, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);
NSString *str = [NSString stringWithFormat:@"%@%@%@",kBitlyWrapperString,escapeStr,kBitlyFootterString];
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
if (data) {
NSString *tempStr = [[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *aDic = [tempStr JSONValue];
NSLog(@"%@",[aDic description]);
NSNumber *errorCode = [aDic objectForKey:@"errorCode"];
NSString *statusCode = [aDic objectForKey:@"statusCode"];
if ([errorCode intValue] == 0 && [statusCode isEqualToString:@"OK"]) {
NSDictionary *results = [[aDic objectForKey:@"results"]objectForKey:longUrl];
NSString *shortUrl = [results objectForKey:@"shortUrl"];
aaa = shortUrl;
} else {
aaa = longUrl;
}
} else {
aaa = longUrl;
}
return aaa;
}

@end

0 件のコメント:

コメントを投稿