SDKで始めるiPad/iPhoneアプリ開発の勘所(4):iOS 4のSDKで、Twitterを使ったiPhoneアプリを作る (1/4) - @IT
SDKで始めるiPad/iPhoneアプリ開発の勘所(4):iOS 4のSDKで、Twitterを使ったiPhoneアプリを作る (2/4) - @IT
ãèªãã ã®ã ãã©ã
NSURLConnectionã使ã£ãéåæHTTPéä¿¡ã¯ããã®è¨äºã®ããã«ã©ããã¼ã¯ã©ã¹ãæ¸ãã¦
- NSMutableDataãå é¨ã§ä¿æ
- éä¿¡éå§æã«åæåãdelegateã¡ã½ããdidReceiveDataãå®è£ ãã¦ç´°åãã«æ¸¡ããã¦ããNSDataãä»ã足ãã¦ããã
- éä¿¡çµäºæãæçµçã«å¾ãããåè¨ã®NSDataã¯Notificationãªã©ã使ã£ã¦å¼ã³åºãå ã«éç¥ããã®å¾NSMutableDataãç ´æ£
ã¨ãã£ããã¨ãããå¿
è¦ããããä½ãã¨ããã©ãããã
大æµã®å ´åã¯éä¸ã®didReceiveDataã§åãåãç´°ããNSDataãªã©ã¯èå³ãªãã"NSURLRequestã渡ãããããã®çµæã¨ãã¦ã®NSDataãåãåãå¦çããã"ã¨ããã ãã ã¨æãã¾ãããã¨ã¨ã©ã¼ãããã°ããã¯ææããã¨ãã¦ã
NSURLConnectionã使ããªãæ¹æ³ã¨ãã¦ä»¥åã«libcurlを使う方法ãæ¸ãã¦ã¿ã¾ãããããã®ä»ã«"Grand Central Dispatch"ã使ã£ã¦éåæã§HTTPéä¿¡ããæ¹æ³ãããã®ã§ç´¹ä»ãã¦ã¿ã¾ãã
HttpClient.h
@interface HttpClient : NSObject { } + (void)request:(NSURLRequest *)request success:(void (^)(NSData *))onSuccess error:(void (^)(NSError *))onError; @end
HttpClient.m
#import "HttpClient.h" @implementation HttpClient + (void)request:(NSURLRequest *)request success:(void (^)(NSData *))onSuccess error:(void (^)(NSError *))onError { dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(q, ^{ NSURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { onError(error); } else { onSuccess(data); } }); } @end
ãããªã¯ã©ã¹ã¡ã½ããä¸ã¤ç¨æãã¦ããã ããå¼ã³åºãå´ã¯
#import "HttpClient.h" ... void (^onSuccess)(NSData *) = ^(NSData *data) { ... }; void (^onError)(NSError *) = ^(NSError *error) { ... }; NSURL *url = [NSURL URLWithString:@"http://example.com/"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [HttpClient request:request success:onSuccess error:onError];
ã®ç¨ã«è¨è¿°ããã
dispatch_async()ã使ãã¨ãã®ä¸ã®ã³ã¼ããããã¯ã¯éåæã§å¦çãããã®ã§ãåæçéä¿¡ãè¡ãNSURLConnectionã®"+sendSynchronousRequest:returningResponse:returningResponse:error:"ã¡ã½ãããå é¨ã§ä½¿ã£ã¦ãã¢ããªå ¨ä½ã¨ãã¦ã®å¦çã¯ãããã¯ãããã«éåæã§éä¿¡ãè¡ããããããã使ãã°ä¸æ°ã«NSDataãåå¾ã§ãããã¨ã©ã¼ãè£è¶³ã§ãããçµäºæã®å¦çããã¡ã½ãããå®ç¾©ãã¦ããã¦ãã®@selectorã渡ãããNSNotificationã使ã£ãããããã¨ãªãããããããã³ã¼ã«ããã¯ã¨ãã¦ã®ã³ã¼ããããã¯ãå®ç¾©ãã¦ããã渡ãã¦ãããã¨ã§ãä½è¨ãªè¨è¿°ãæ¸ããããPerlã§ããã¨ã¾ãã«AnyEvent::HTTPã®ãããªä½¿ãæ¹ãã§ããããã§ãã
iOS 4(Macã ã¨OS 10.6)ããã®æ©è½ãªã®ã§3.xç³»ã®ãã¨ãèããã¨ä½¿ããªãã§ãã(NSOperationã¨ã使ãã°è¿ããã¨ã¯ã§ããâ¦ã®ããªï¼)ã4åãã®ã¢ããªã¨ãã¦èãããªãä¸è¨ã®æ¹æ³ã¯ã¨ã¦ãç°¡åã«æ¸ãã¦ã©ã¯ã«ä½¿ããã®ã§ä¾¿å©ãªã®ã§ã¯ãªãã§ããããã