AFNetworking 初探

AFNetworking 初探

繼ASIHTTPRequest發佈再也不維護的訊息之後,若是我們不使用CDN(雲端伺服器),AFNetworking 會是一套不錯的選擇。
下載網址:https://github.com/AFNetworking/AFNetworkinggit

下載之後,直接匯入Xcode的專案便可以用,記得加入SystemConfiguration.frameworkgithub

範例參考:

在application: didFinishLaunchingWithOptions: 加入AFNetworkActivityIndicatorManager
記得 #import 「AFNetworkActivityIndicatorManager.h"
app

- (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"dom

    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"
簡單的作法,是url

[imageView setImageWithURL:@"圖片的絕對路徑"];

複雜的作法,能夠在圖片下載完成之後,再去觸發一些事件spa

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"");
}];
相關文章
相關標籤/搜索