まずはBitlyShortURL.h
#import <Foundation/Foundation.h>
@interface BitlyShortURL : NSObject <NSXMLParserDelegate>
{
NSString *_baseURL; //短縮される元URL
NSString *_resultURL; //APIによって短縮されたURL
}
- (id)initWithLongURL:(NSString *)longURL; //元URLを使って初期化
- (NSString *)parse; //パースして短縮URLを返す
@end
次にBitlyShortURL.m
パースされた要素の通り、他にも色々な情報があるがとりあえず短縮URLを手に入れたい!って時にこれから始める。
#import "BitlyShortURL.h"
static NSString *kBitlyWrapperString = @"http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl=";
static NSString *kBitlyFootterString = @"&login=ログイン名&apiKey=APIキー";
@implementation BitlyShortURL
- (NSString *)returnLink:(NSString *)str{
return (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);
}
- (id)initWithLongURL:(NSString *)longURL{
self = [super init];
if (self) {
NSString *str = [NSString stringWithFormat:@"%@%@%@",kBitlyWrapperString,[self returnLink:longURL],kBitlyFootterString];
_baseURL = [[NSString alloc]initWithString:str];
NSLog(@"%@",_baseURL);
_resultURL = @"error";
}
return self;
}
- (NSString *)parse{
NSURL *url = [NSURL URLWithString:_baseURL];
NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
if (_resultURL == nil) {
_resultURL = @"error";
}
return _resultURL;
}
- (void)dealloc{
[_baseURL release],_baseURL = nil;
[_resultURL release],_resultURL = nil;
[super dealloc];
}
#pragma mark -
#pragma mark NSXMLParserDelegate Protocol
- (void)parserDidStartDocument:(NSXMLParser *)parser{
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
NSLog(@"<%@>",elementName);
if ([elementName isEqualToString:@"shortUrl"]) {
[_resultURL release],_resultURL = nil;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(@"%@",string);
if (_resultURL == nil) {
_resultURL = [[NSString alloc]initWithString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(@"</%@>",elementName);
}
@end
0 件のコメント:
コメントを投稿