ポスト ASIHTTPRequest と注目されているネットワークライブラリ。
並列実行に NSOperation を使い Blocks を使った APIを提供している。
用意されているクラス、プロトコル、カテゴリの一覧
AFHTTPClient
AFHTTPRequestOperation
AFImageCache
AFImageRequestOperation
AFJSONRequestOperation
AFNetworkActivityIndicatorManager
AFPropertyListRequestOperation
AFURLConnectionOperation
AFXMLRequestOperation
Protocol References
AFMultipartFormData
UIImageView(AFNetworking)
基本となるHTTPアクセスの他、画像のキャッシュや JSON/XML/PropertyList処理なども用意されている。
以下、READMEから抜粋。
// JSON Request
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"https://gowalla.com/users/mattt.json"]];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Name: %@ %@", [JSON valueForKeyPath:@"first_name"],
[JSON valueForKeyPath:@"last_name"]);
} failure:nil];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
データの種類ごと(上記例は JSON)に用意された AFHTTPRequestOperation を作成し、ここに Blocksで成功時の処理を書いておく。それを最後に NSOperationQueue へ投入するだけ。いくつかステップを踏む必要はあるが元々の NSOperation系APIを素直に活用しているので汎用性がある(あ、 JSONライブラリを別途用意する必要も無いのか)。
// Image Request
UIImageView *imageView = [[UIImageView alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
URLから画像を取得して直接 UIImageViewを作成するメソッドもある。これは簡単でいいかも。
// File Upload with Progress Callback
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [[AFHTTPClient sharedClient]
multipartFormRequestWithMethod:@"POST" path:@"/upload"
parameters:nil constructingBodyWithBlock: ^(id formData) {
[formData appendPartWithFileData:data mimeType:@"image/jpeg" name:@"avatar"];
}];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
[operation setUploadProgressBlock:
^(NSUInteger totalBytesWritten, NSUInteger totalBytesExpectedToWrite) {
NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
POST/マルチパートによるファイルアップロード処理。簡潔でわかりやすい。setUploadProgressBlock: で進捗状況をハンドリング可能。
- - - -
比較的抽象度が高く複雑な記述なしに簡単に利用できそう。ASIHTTPRequest が機能を重ねていってAPIが肥大化気味で複雑になってしまったのに対し、よく使われる機能だけに的を絞ったある意味潔いシンプルなAPI思想が個人的には気に入った。実際に使って試してみたい。
参考情報
AFNetworking Reference
AFNetworking のリファンレンスマニュアル(appledoc)
iPhone アプリ開発コミュニティのネットワークライブラリが ASIHTTPRequest から AFNetworking への移行の流れ? - laiso - iPhoneアプリ開発グループ
...と、いうことらしい。ASIHTTPRequest のメンテが終了とは知らなかった。うーむ。
人気があるのは確かなようで GitHub の Weekly/Monthly Most Wached Project としても最近上位に来ている。
watch と fork は 1,283 123 と ASIHTTPRequest にはまだ及ばないものの相当数ある。
Gowalla Engineering / AFNetworking: A Delightful Networking Library for iOS and Mac OS X
AFNetworkingの解説記事。