iOS開發 - AFNetworking網路請求
AFNetworking
什麼是AFN
全稱是AFNetworking,是對NSURLConnection、NSURLSession的一層封裝
雖然運行效率沒有ASI高,但是使用比ASI簡單
在iOS開發中,使用比較廣泛
AFHTTPRequestOperationManager
是AFN中最重要的對象之一
封裝了HTTP請求的常見處理
GETPOST請求
解析伺服器的響應資料
建立
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
GETPOST請求
//GET請求- (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure//POST請求- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
檔案上傳
- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
監控連網狀態
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];[manager startMonitoring];[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@%d, status);}];
提示:要監控網路連接狀態,必須要先調用單例的startMonitoring方法
1.AFHTTPRequestOperationManager
* 對NSURLConnection的封裝
2.AFHTTPSessionManager
* 對NSURLSession的封裝
對伺服器返回資料的解析
1.AFN可以自動對伺服器返回的資料進行解析* 預設將伺服器返回的資料當做JSON來解析2.設定對伺服器返回資料的解析方式1> 當做是JSON來解析(預設做法)* mgr.responseSerializer = [AFJSONResponseSerializer serializer];* responseObject的類型是NSDictionary或者NSArray2> 當做是XML來解析* mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];* responseObject的類型是NSXMLParser3> 直接返回data* 意思是:告訴AFN不要去解析伺服器返回的資料,保持原來的data即可* mgr.responseSerializer = [AFHTTPResponseSerializer serializer];3.注意* 伺服器返回的資料一定要跟responseSerializer對得上1> 伺服器返回的是JSON資料* AFJSONResponseSerializer* AFHTTPResponseSerializer2> 伺服器返回的是XML資料* AFXMLParserResponseSerializer* AFHTTPResponseSerializer3> 伺服器返回的是其他資料* AFHTTPResponseSerializer
AFNetworking網路請求執行個體
#import AFNetworking.h@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self postJSON];}- (void)getSession{ // AFHTTPSessionManager 對 NSURLSession 的封裝 AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; [mgr GET:@ parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) { } failure:^(NSURLSessionDataTask *task, NSError *error) { }];}/** * 利用AFN發送一個POST請求,伺服器返回的JSON資料 */- (void)postJSON{ // AFHTTPRequestOperationManager 對 NSURLConnection的封裝 // 1.建立一個請求操作管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.請求參數 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@username] = @哈哈哈; params[@pwd] = @123; // 3.發送一個GET請求 NSString *url = @http://localhost:8080/MJServer/login; [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 請求成功的時候調用這個block NSLog(@請求成功---%@, responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 請求失敗的時候調用調用這個block NSLog(@請求失敗); }];}/** * 利用AFN發送一個GET請求,伺服器返回的JSON資料,讓AFN直接返回data */- (void)getData{ // 1.建立一個請求操作管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 聲明:不要對伺服器返回的資料進行解析,直接返回data即可 // 如果是檔案下載,肯定是用這個 // responseObject的類型是NSData mgr.responseSerializer = [AFHTTPResponseSerializer serializer]; // 2.請求參數 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@username] = @哈哈哈; params[@pwd] = @123; // 3.發送一個GET請求 NSString *url = @http://localhost:8080/MJServer/login; [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 請求成功的時候調用這個block NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil]; NSLog(@%@, dict); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 請求失敗的時候調用調用這個block NSLog(@請求失敗); }];}/** * 利用AFN發送一個GET請求,伺服器返回的XML資料 */- (void)getXML{ // 1.建立一個請求操作管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 聲明:等會伺服器返回的是XML資料 // responseObject的類型是NSXMLParser mgr.responseSerializer = [AFXMLParserResponseSerializer serializer]; // 2.請求參數 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@username] = @哈哈哈; params[@pwd] = @123; params[@type] = @XML; // 3.發送一個GET請求 NSString *url = @http://localhost:8080/MJServer/login; [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 請求成功的時候調用這個block NSLog(@請求成功--%@, responseObject);// responseObject.delegate = self;// [responseObject parse]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 請求失敗的時候調用調用這個block NSLog(@請求失敗); }];}/** * 利用AFN發送一個GET請求,伺服器返回的JSON資料 */- (void)getJSON{ // 1.建立一個請求操作管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 聲明一下:伺服器返回的是JSON資料 // mgr.responseSerializer = [AFJSONResponseSerializer serializer]; // responseObject的類型是NSDictionary或者NSArray // 2.請求參數 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@username] = @哈哈哈; params[@pwd] = @123; // 3.發送一個GET請求 NSString *url = @http://localhost:8080/Server/login; [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 請求成功的時候調用這個block NSLog(@請求成功---%@, responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 請求失敗的時候調用調用這個block NSLog(@請求失敗); }];}@end
AFNetworking檔案上傳執行個體
#import AFNetworking.h@interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *imageView;- (IBAction)upload;@end@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@請選擇圖片 delegate:self cancelButtonTitle:@取消 destructiveButtonTitle:nil otherButtonTitles:@拍照, @相簿, nil]; [sheet showInView:self.view.window];}#pragma mark - UIActionSheet- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; // 設定代理 ipc.delegate = self; switch (buttonIndex) { case 0: { // 拍照 if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return; ipc.sourceType = UIImagePickerControllerSourceTypeCamera; break; } case 1: { // 相簿 if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return; ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; break; } default: break; } // 顯示控制器 [self presentViewController:ipc animated:YES completion:nil];}#pragma mark - UIImagePickerControllerDelegate/** * 在選擇完圖片後調用 * * @param info 裡麵包含了圖片資訊 */- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ // 銷毀控制器 [picker dismissViewControllerAnimated:YES completion:nil]; // 獲得圖片 UIImage *image = info[UIImagePickerControllerOriginalImage]; // 顯示圖片 self.imageView.image = image;}- (void)upload1{ // 1.建立一個管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.封裝參數(這個字典只能放非檔案參數) NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@username] = @123; params[@age] = @20; params[@pwd] = @456; params[@height] = @1.55; // 2.發送一個請求 NSString *url = @http://localhost:8080/MJServer/upload; [mgr POST:url parameters:params constructingBodyWithBlock:^(id formData) { // 在發送請求之前會自動調用這個block // 需要在這個block中添加檔案參數到formData中 /** FileURL : 需要上傳的檔案的URL路徑 name : 伺服器那邊接收檔案用的參數名 fileName : (告訴伺服器)所上傳檔案的檔案名稱 mimeType : 所上傳檔案的檔案類型 */ NSURL *url = [[NSBundle mainBundle] URLForResource:@itcast withExtension:@txt]; [formData appendPartWithFileURL:url name:@file fileName:@test.txt mimeType:@text/plain error:nil]; /** FileData : 需要上傳的檔案的具體資料 name : 伺服器那邊接收檔案用的參數名 fileName : (告訴伺服器)所上傳檔案的檔案名稱 mimeType : 所上傳檔案的檔案類型 */ // UIImage *image = [UIImage imageNamed:@minion_01]; // NSData *fileData = UIImagePNGRepresentation(image); // [formData appendPartWithFileData:fileData name:@file fileName:@haha.png mimeType:@image/png]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@上傳成功); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@上傳失敗); }];}- (IBAction)upload { if (self.imageView.image == nil) return; // 1.建立一個管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.封裝參數(這個字典只能放非檔案參數) NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@username] = @123; params[@age] = @20; params[@pwd] = @456; params[@height] = @1.55; // 2.發送一個請求 NSString *url = @http://192.168.15.172:8080/Server/upload; [mgr POST:url parameters:params constructingBodyWithBlock:^(id formData) { NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0); [formData appendPartWithFileData:fileData name:@file fileName:@haha.jpg mimeType:@image/jpeg]; // 不是用這個方法來設定檔案參數// [formData appendPartWithFormData:fileData name:@file]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@上傳成功); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@上傳失敗); }]; // 檔案下載,檔案比較大,斷點續傳技術:普遍所有的HTTP伺服器都支援 // 檔案上傳,檔案比較大,斷點續傳技術:一般的HTTP伺服器都不支援,常用的技術用的是Socket(TCPIP、UDP)}@end