iOS學習之第三方-AFNetworking1.3.0,iosafnetworking
將 CocoaPods 安裝後,按照 CocoaPods 的使用說明就可以將 AFNetworking 第三方整合到工程中,具體請看上篇部落格iOS學習46之第三方CocoaPods的安裝和使用(通用方法)
AFNetworking簡介
AFNetworking是一個 在iOS開發中 使用非常多網路開源庫,是一個輕量級的網路請求API類庫。
適用於iOS以及Mac OS X。它構建於在(Apple iOS開發文檔) NSURLSession , NSOperation , 以及其他熟悉的Foundation技術之上,核心代碼: AFHTTPSessionManager。
它擁有良好的架構,豐富的api,以及模組化構建方式,使得使用起來非常輕鬆。
官方連結http://cocoadocs.org/docsets/AFNetworking/1.3.0/
AFHTTPSessionManager
AFHTTPSessionManager是核心網路請求的管理類,用於管理 GET 和 POST 請求
AFHTTPSessionManager對象的聲明和懶載入代碼:
#import "ViewController.h"// 網路的要求標頭檔案#import <AFNetworking/AFNetworking.h>@interface ViewController ()/// 用於網路請求的session對象@property (nonatomic, strong) AFHTTPSessionManager *session;@end@implementation ViewController// 懶載入- (AFHTTPSessionManager *)session{ if (!_session) { _session = [AFHTTPSessionManager manager]; // 佈建要求介面回來的時候,支援什麼類型的資料 _session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil]; } return _session;}@end
AFNetworking進行網路監測
在進行網路監測的時候,首先應該先判斷網路監測是否開啟,如果沒有開啟,先要開啟監測
- (void)startMonitoring; // 開啟網路監測- (void)stopMonitoring; // 關閉網路監測
接下來就判斷當前的網路狀態,AFNetworking有幾種不同的網路狀態
// 幾種不同的網路狀態typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { AFNetworkReachabilityStatusUnknown = -1, // 當前網路處於未知狀態,手機沒有訊號 AFNetworkReachabilityStatusNotReachable = 0, // 當前網路處於未串連狀態,手機沒有開流量或開WiFi AFNetworkReachabilityStatusReachableViaWWAN = 1, // 手機流量網路 AFNetworkReachabilityStatusReachableViaWiFi = 2, // WiFi狀態};
執行個體代碼:
#pragma mark - 網路監測按鈕的回應程式法- (IBAction)networkMonitoringAction:(UIButton *)sender{ if (!isOPen) { // 開啟網路監測的方法 [[AFNetworkReachabilityManager sharedManager] startMonitoring]; isOPen = YES; } else { // 關閉網路監測 [[AFNetworkReachabilityManager sharedManager] stopMonitoring]; isOPen = NO; } // 接下來判斷當前是WiFi狀態還有3g狀態,網路不可用狀態 [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusUnknown: NSLog(@"當前網路處於未知狀態,手機沒有訊號"); break; case AFNetworkReachabilityStatusNotReachable: NSLog(@"當前網路處於未串連狀態,手機沒有開流量或開WiFi"); break; case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"手機流量網路"); break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"WiFi狀態"); break; default: break; } }];}
AFNetworking的GET請求
AFNetworking1.3.0 不再想以前一樣一個 GET 請求需要很多的類參與,這裡這需要一個 AFHTTPSessionManager 的方法就可以完成
方法:
- (NSURLSessionDataTask *)GET:(NSString *)URLString // get請求的網址 parameters:(id)parameters // 拼接的參數 progress:(void (^)(NSProgress * _Nonnull))downloadProgress // 下載的進度 success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success // 請求成功 failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure // 請求失敗
執行個體代碼:
#pragma mark - GET請求的回應程式法- (IBAction)getRequestAction:(id)sender{ [self.session GET:@"http://api.yhouse.com/m/city/dynmiclist" // get請求的網址 parameters:nil // 拼接的參數 progress:^(NSProgress * _Nonnull downloadProgress) { // 下載的進度 NSLog(@"下載的進度"); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // 請求成功 NSLog(@"請求成功"); // 處理資料... NSDictionary *reusltDict = responseObject[@"data"]; NSArray *resultArray = reusltDict[@"allCity"]; for (NSDictionary *dict in resultArray) { NSLog(@"name = %@", dict[@"name"]); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { // 請求失敗 NSLog(@"請求失敗"); }];}
AFNetworking的POST請求
同GET請求一樣,POST請求也是如此,不過POST請求需要拼接參數,一般情況下參數為一個字典
方法:
- (NSURLSessionDataTask *)POST:(NSString *)URLString // post請求的網址 parameters:(id)parameters // 拼接的參數body progress:(void (^)(NSProgress * _Nonnull))uploadProgress // 上傳的進度 success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success // 請求成功 failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure // 請求失敗
執行個體代碼:
#pragma mark - POST請求的回應程式法- (IBAction)postRequestAction:(id)sender{ NSString *urlStr = @"http://m.taskwedo.com/API/wedo1/wedo.php"; NSMutableDictionary *dict = @{ @"do" : @"pri_memberlist", @"member_id" : @"zpHr2dsRvQQxYJxo2", @"workspace_id" : @"ILfYpE4Dhs2gWcuQx" }.mutableCopy; [self.session POST:urlStr // post請求的網址 parameters:dict // 拼接的參數body progress:^(NSProgress * _Nonnull uploadProgress) { // 上傳的進度 NSLog(@"上傳的進度"); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // 請求成功 NSLog(@"請求成功"); NSDictionary *reusltDict = responseObject[@"res"]; NSArray *keyArray = reusltDict.allKeys; for (NSString *key in keyArray) { NSArray *resultArray = reusltDict[key]; for (NSDictionary *dict in resultArray) { NSLog(@"username = %@", dict[@"username"]); } } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { // 請求失敗 NSLog(@"請求失敗"); }];}
注意:URL字串或body體中如果有特殊字元或者中文字元,AFNETWorking並沒有做UTF8的轉碼,需要:
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];commonContent = [commonContent stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
代碼執行個體:
#pragma mark - POST請求2的回應程式法- (IBAction)postRequest2Action:(id)sender{ NSString *urlStr = @"http://m.taskwedo.com/API/wedo1/wedo.php"; NSString *commonContent = @"類別模組計劃用到第三部分中,待提問、回答積累到一定數量時,便於大家的問題的快速尋找,所以提問部分暫時不加入這個"; commonContent = [commonContent stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; // 當body體或URL中出現漢字時使用 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setValue:@"" forKey:@"address"]; [dict setValue:commonContent forKey:@"comment"]; [dict setValue:@"add_comment" forKey:@"do"]; [dict setValue:@"task" forKey:@"kind"]; [dict setValue:@"zpHr2dsRvQQxYJxo2" forKey:@"member_id"]; [dict setValue:@"" forKey:@"other"]; [dict setValue:@"55a47e79ec25e3641" forKey:@"task_id"]; [self.session POST:urlStr parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"上傳成功"); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"請求成功:%@", responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗"); }];}