1.AFNetworking源碼文件:
2.所需Library:
二、簡單的使用流程:
//具體的後臺服務地址
static NSString *const BaseURLString = @"www.xx.com/";
/*****************用法一*********************/
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
//用於存放需要傳遞給服務端的參數
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:1];
[parameters setObject:參數值 forKey:參數名];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"];
NSString *path = @"具體的服務端處理接口";//例如restful的"xx/yy/zz"
/*發送請求。可以使用getPath來獲取數據,也可以用postPath來更新服務器數據,
這裏只列舉了post的用法,get與post的寫法類似。*/
[client postPath:path
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//交互成功:responseObject包含了從服務器回傳的信息
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//交互失敗:error記錄了具體的錯誤信息
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"獲取數據失敗"
message:error
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
}
];
/*****************用法二(operation的方式)*********************/
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BaseURLString,@"具體的服務端處理接口"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:baseURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0f];
//傳遞的參數
NSString *postString = @"keywords=嘟囔";
NSStringEncoding enc = NSUTF8StringEncoding;
NSData *postData = [postString dataUsingEncoding: enc allowLossyConversion: YES];
//設置Method
[request setHTTPMethod: @"POST"];
//裝載內容
[request setHTTPBody:postData];
AFJSONRequestOperation *operation
= [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
//交互成功:JSON包含了從服務器回傳的信息
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
//交互失敗:error記錄了具體的錯誤信息
NSLog(@"ERROR: %@", error);
}];
[operation start];
這兩種方式,都可以寫在自己的網絡數據交互類裏面,然後也封裝一個block方法,將從服務器端成功獲取到的數據傳遞給具體的controller用於顯示。
三、UIImageView+AFNetworking
這個東東很好用。可以異步的加載網絡圖片。
具體的用法也很簡單:
#import "UIImageView+AFNetworking.h"
[需要異步加載圖片的imageView setImageWithURL:[NSURL URLWithString:圖片存放的可訪問的網絡地址] placeholderImage:[UIImage imageNamed:placeholder圖片]];
有什麼好的使用建議,大家可以共同討論。