AFHTTPSessionManager:
根据这个对象可以对请求千设置一些参数和状态
//得到一个session manager AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; NSOperationQueue *operationQueue = [manager operationQueue]; // 判断网络状态 [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusReachableViaWWAN: case AFNetworkReachabilityStatusReachableViaWiFi: { [operationQueue setSuspended:NO]; } break; case AFNetworkReachabilityStatusNotReachable: default: { [operationQueue setSuspended:YES]; } break; } }];
发送请求以GET为例子:
[manager GET:@"http://apis.baidu.com/apistore/iplookupservice/iplookup" parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSString *str = responseObject ; NSLog(@"suc >>>%@" ,[NSThread currentThread]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }];
这里的Block块在主线程,因为底层已经处理了
这是指定String 类型的URL 还可以不用系统帮我们封装,自己构造request
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:httpUrl parameters:[NSDictionary dictionaryWithObjectsAndKeys:@"117.89.35.58",@"ip" ,nil] error:nil]; [request addValue:@"5560971e1657a727c71e04ce5b145798" forHTTPHeaderField:@"apikey"];
建议Request用AF建议的方法构造,AFHTTPRequestSerializer 用于构造序列化的Request,然后交给AFHTTPSessionManager处理得到一个NSURLSessionDataTask
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { // NSLog(@"res ===%@" , responseObject); NSLog(@"suc >>>%@" ,[NSThread currentThread]); NSDictionary *dic = responseObject; NSLog(@"dic ==%@" ,dic); }];
这里回调也是主线程
NSURLSessionDataTask有两个方法用来控制任务状态
- (void)suspend;
- (void)resume;
得到NSURLSessionDataTask之后默认状态是Suspend必须调用resume
AFJSONResponseSerializer 默认初始化@"application/json", @"text/json", @"text/javascript"有这几种,如果内容格式为就会报错@"text/plain",解决办法就是添加进去就行了