AFNetworking 初探
AFNetworking 初探
繼ASIHTTPRequest發佈不再維護的訊息之後,如果我們不使用CDN(雲端伺服器),AFNetworking 會是一套不錯的選擇。
下載網址:https://github.com/AFNetworking/AFNetworking
下載之後,直接匯入Xcode的專案即可以用,記得加入SystemConfiguration.framework
範例參考:
在application: didFinishLaunchingWithOptions: 加入AFNetworkActivityIndicatorManager
記得 #import “AFNetworkActivityIndicatorManager.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
這是我們常用的下載網路資源(JSON 格式)
記得
#import “AFHTTPClient.h"
#import “AFHTTPRequestOperation.h"
#import “JSONKit.h"
NSURL *url = [NSURL URLWithString:@"http://www.domain.com"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; NSString *_path=[NSString stringWithFormat:@"/user_login/%@/%@/",userName,password]; NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:_path parameters:nil]; [httpClient release]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { //下載成功之後,使用JSONKit將字串轉成NSDictionary或NSArray 格式 NSDictionary *deserializedData = [operation.responseString objectFromJSONString]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //下載失敗之後處理 }]; NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; [queue addOperation:operation];
我門做完上一個步驟,有時候會得到一些圖片的絕對網址,接下來就是根據這些網址,進行非同步下載圖片。
記得 #import “UIImageView+AFNetworking.h"
簡單的做法,是
[imageView setImageWithURL:@"圖片的絕對路徑"];
複雜的做法,可以在圖片下載完成之後,再去觸發一些事件
NSURL *url = [NSURL URLWithString:@"圖片的絕對路徑"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; [imageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { NSLog(@"圖片下載成功!do something"); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { NSLog(@"圖片無法下載!do something""); }];