AFNetworking主要用來處理網絡請求的,是用的比較廣泛的一個架構,下面來簡單介紹AFNetworking的使用;
一、導入頭檔案:
#import "AFNetworking.h"
AFN的架構可以通過coocapods導入:
pod 'AFNetworking'
二、使用AFN的方法:
-(void)test {
AFHTTPSessionManager *httpSession = [AFHTTPSessionManager manager];
httpSession.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
parameter[@"參數名"] = @"參數的值";
//例如:parameter[@"name"] = @"test";
[httpSession POST:@"發送請求的網址" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//網絡請求成功的傳回事件
//接受JSON資料類型,也可以是NSArray,亦可以是NSString
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//例如: NSArray *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//網絡請求失敗的傳回事件
}];
}
在需要發送請求的時候調用這個方法就可以了,AFN也有GET的方法,使用方法和原理和POST差不多:
[httpSession GET:@"發送請求的網址" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];