9/25/2011

短縮URLを展開するNSString (expandURL) カテゴリ

短縮URLを見ない日はなくなった。
Twitterなどは自前でt.coなる短縮URLを用意して悪意のある短縮URLからユーザーを守ろうという試みも行われている。また、アクセスの解析も行われているようだ。

iOSアプリケーションを開発する上では、短縮URLを展開して元URLのURLスキームを解析することにより、UIApplicationの-(BOOL)OpenURL:(NSURL *)メソッドを使用するか否かの判断が可能になる。
これを使用するとSafariやその他の外部アプリケーションが起動されるため、ユーザーが自前のアプリケーションから離れてしまうからだ。

この短縮URLを展開してくれるAPIが幾つか存在するので、その中の2つを使ってNSStringのカテゴリとしてまとめてみた。

APIが返す値はJSON形式で返ってくるものを選び、SBJSONを利用してNSDictionary形式に変換、後続の処理を行なっている。失敗した場合は展開前の短縮URLが返るようにしてある。展開できる短縮URLの種類はAPIに依存しているので注意されたし。またAPIサービスそのものの業務継続性にも注意が必要。

NSString+expandURL.h

#import <Foundation/NSString.h>

@interface NSString (expandURL)
+ (NSString *)expandURL:(NSString *)urlStr;
@end

NSString+expandURL.m

#import "NSString+expandURL.h"
#import "SBJson.h"

@implementation NSString (expandURL)

+ (NSString *)expandURL:(NSString *)urlStr{
NSString *str = nil;
NSURL *url = nil;
NSData *data = nil;
NSString *aaa = nil;
str = [NSString stringWithFormat:@"http://api.unshort.me/?r=%@&t=json",urlStr];
url = [NSURL URLWithString:str];
data = [NSData dataWithContentsOfURL:url];
if (data) {
NSString *result = [[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *aDic = [result JSONValue];
NSString *status = [aDic objectForKey:@"success"];
if ([status isEqualToString:@"true"]){
aaa = [aDic objectForKey:@"resolvedURL"];
} else {
aaa = urlStr;
}
} else {
str = [NSString stringWithFormat:@"http://expandurl.appspot.com/expand?url=%@",urlStr];
url = [NSURL URLWithString:str];
data = [NSData dataWithContentsOfURL:url];
if (data) {
NSString *result = [[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *aDic = [result JSONValue];
NSString *status = [aDic objectForKey:@"status"];
if ([status isEqualToString:@"OK"]){
aaa = [aDic objectForKey:@"end_url"];
} else {
aaa = urlStr;
}
} else {
aaa = urlStr;
}
}
return aaa;
}

@end

1 件のコメント:

  1. Based on this sample, an digital circuit can decide the place of the reel. Roll-up is the process of dramatizing a win by half in} sounds while the meters count as much as} the amount that has been received. The picks routinely find yourself at a spherical quantity like seven-hundred or 2100, therefore my thinking it’s predetermined, so I just tried to race via it as fast as attainable to get back to the reels to try to get one other one. Yeager, bet365 who now mentors lively responsibility members with playing addictions, says he hasn't heard that anything has changed. Controls by themselves could not at all times be enough when access to slots are just steps away.

    返信削除