1.AFNetWorking簡介
AFNetworking是一個在IOS開發中使用非常多網絡開源庫,適用於iOS以及Mac OS X. 它構建於(apple iOS開發文檔)NSURLConnection, NSOperation,以及其他熟悉的Foundation技術之上。它擁有良好的架構,豐富的API,以及模塊化構建方式,使得使用起來非常輕鬆.
AFURLConnectionOperation:繼承自 NSOperation 實現了NSURLConnection 的代理方法.
AFHTTPRequestOperation: 繼承自 AFURLConnectionOperation的子類,當request請求使用的協議爲HTTP和HTTPS時使用,它封裝了用於決定request是否成功的狀態碼和內容類型.
AFJSONRequestOperation: 繼承自AFHTTPRequestOperation,用於下載和處理json response數據.
AFXMLRequestOperation:繼承自AFHTTPRequestOperation,用於下載和處理xml response數據.
AFPropertyListRequestOperation:繼承自AFHTTPRequestOperation,用於下載和處理property list response數據.
AFHTTPClient:是一個封裝了基於http協議的網絡應用程序的公共交流模式.包含
(1).發起基於根路徑的使用基本的url相關路徑來只做request
(2).爲request自動添加設置http headers.
(3).使用http 基礎證書或者OAuth來驗證request
(4).爲由client製作的requests管理一個NSOperationQueue
(5).從NSDictionary生成一個查詢字符串或http bodies.
(6).從request中構建多部件
(7).自動的解析http response數據爲相應的表現數據
(8).在網絡可達性測試用監控和響應變化.
AFNetWorking的下載地址:https://github.com/AFNetworking/AFNetworking
2.AFNetWorking的使用
(1) 將AFNetWorking文件夾導入項目
(2) 添加類庫 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework
(3) 在使用的地方 #import "AFNetworking.h"
(4)解決編譯時警告:
//Prefix.pch文件中加入
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>
注:AFNetWorking採用ARC ,在不使用ARC項目中使用時,對AFNetWorking的所有.m文件添加“-fobjc-arc”
在使用ARC項目中,使用“不使用ARC”的類庫時,對類庫的.m文件添加“-fno-objc-arc”
(5)
static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";
NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];
NSURL *url = [NSURLURLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperationJSONRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) {
NSDictionary*dicWeather = (NSDictionary *)JSON;
NSLog(@"result:%@",dicWeather);
} failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather" message:[NSStringstringWithFormat:@"%@",error] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];}];
[operation start];
1)根據基本的URL構造除完整的一個URL,然後通過這個完整的URL獲得一個NSURL對象,然後根據這個url獲得一個NSURLRequest。
2)AFJSONRequestOperation是一個完整的類,整合了從網絡中獲取數據並對JSON進行解析。
3)當請求成功,則運行成功塊。在本例中,把解析出來的天氣數據從JSON變量轉換爲一個字典(dictionary),並將其存儲在字典中。
4)如果運行出問題了,則運行失敗塊(failure block),比如網絡不可用。如果failure block被調用了,將會通過提示框顯示錯誤信息。
(6).AFNetWorking異步加載圖片
#import “UIImageView+AFNetworking.h”
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];
__weak UIImageView *_imageView = imageView;
[imageViewsetImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request,NSHTTPURLResponse *response, UIImage *image) {
_imageView.image = image;
[_imageView setNeedsDisplay];
} failure:^(NSURLRequest *request, NSHTTPURLResponse*response, NSError *error) { }];
[self.view addSubview:imageView];
(7).GET 和POST請求
1).構建一個baseURL,以及一個參數字典,並將這兩個變量傳給AFHTTPClient.
2).將AFJSONRequestOperation註冊爲HTTP的操作, 這樣就可以跟之前的示例一樣,可以獲得解析好的JSON數據。
3).做了一個GET請求,這個請求有一對block:success和failure。
4).POST請求跟GET一樣
AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[clientregisterHTTPOperationClass:[AFJSONRequestOperation class]];
[clientsetDefaultHeader:@"Accept" value:@"application/json"];
[client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather =responseObject;
self.title = @"HTTPPOST";
[self.tableViewreloadData]; } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSStringstringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
[client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather =responseObject;
self.title = @"HTTP GET";
[self.tableViewreloadData]; } failure:^(AFHTTPRequestOperation *operation, NSError*error) { UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSStringstringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}]; <strong> </strong>
(8)狀態欄設置
在Appdelegate裏面- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加 [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];//用來給用戶做出網絡訪問的提示。
(9)請求超時設置
timeout和參數都是在NSURLRequest/NSMutableURLRequest設置的
NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"/" parameters:nil];//這裏的parameters:參數就是你的第二個問題如何設置參數
[request setTimeoutInterval:120];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^{...} failure:^{...}];
[client enqueueHTTPRequestOperation:operation];
如果你是繼承了AFHTTPClient
就需要override一個方法requestWithMethod
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters{
NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
[request setTimeoutInterval:15];
return request;
}
[self postPath:@"" parameters:nil //參數
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success((AFJSONRequestOperation *)operation, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure((AFJSONRequestOperation *)operation, error);
}
}];
轉載兩篇其他大師的博文:
AFNetWorking2.0的使用:http://blog.csdn.net/daiyelang/article/details/38421341
AFNetWorking2.5的使用:http://blog.csdn.net/daiyelang/article/details/38434023
AFNetWorking2.0新特性講解之AFHTTPSessionManager:http://www.360doc.com/content/13/1217/09/14615320_337780262.shtml
AFNetWorking框架使用淺析:http://wenku.baidu.com/link?url=RbK27v4ZabX1ezY6FXn8gvcIFJXpVesi-zZHFP2DQ_cuv7cT1pIr13GzOdpUBo7B30BC0N2TjvnnSKi3u_BMJ9jlZ5ZC_gEfPqepOtsFsAu