[iOS 多线程 & 网络 - 4.0] - AFN框架简单使用
- AFNetworking
- 是对NSURLConnection的封装
- 运行效率没有ASI高(因为ASI基于CFNetwork),但是使用简单
- AFN支持ARC
1 /** 发送 GET/POST 请求 */ 2 - (void) sendNormalRequest { 3 // 1.创建请求 管理者 4 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 5 6 // 2.设置参数 7 NSMutableDictionary *param = [NSMutableDictionary dictionary]; 8 param[@"user"] = @"tom"; 9 param[@"password"] = @"123"; 10 11 // 3.发送请求 12 // // 3.1 GET请求 13 // [manager GET:@"http://192.168.0.21:8080/MyTestServer/login" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) { 14 // NSLog(@"请求成功"); 15 // NSLog(@"%@", responseObject); 16 // } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 17 // NSLog(@"请求失败"); 18 // NSLog(@"%@", error); 19 // }]; 20 21 // 3.2 POST请求 22 [manager POST:@"http://192.168.0.21:8080/MyTestServer/login" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) { 23 NSLog(@"请求成功"); 24 NSLog(@"%@", responseObject); 25 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 26 NSLog(@"请求失败"); 27 NSLog(@"%@", error); 28 }]; 29 }
1 #import <Foundation/Foundation.h> 2 3 @implementation NSDictionary (Log) 4 5 /** 本地化显示 */ 6 - (NSString *)descriptionWithLocale:(id)locale { 7 NSMutableString *str = [NSMutableString string]; 8 9 [str appendString:@"{\n"]; 10 11 // 遍历字典 12 [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 13 [str appendFormat:@"\t%@ = %@,\n", key, obj]; 14 }]; 15 16 [str appendString:@"}"]; 17 18 // 取出最后一个“,” 19 NSRange range = [str rangeOfString:@"," options:NSBackwardsSearch]; 20 [str deleteCharactersInRange:range]; 21 22 return str; 23 } 24 25 @end 26 27 @implementation NSArray (Log) 28 29 - (NSString *)descriptionWithLocale:(id)locale { 30 NSMutableString *str = [NSMutableString string]; 31 32 [str appendString:@"[\n"]; 33 34 // 遍历数组所有元素 35 [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 36 [str appendFormat:@"%@, \n", obj]; 37 }]; 38 39 [str appendString:@"]"]; 40 41 return str; 42 } 43 44 @end
- AFHTTPRequestOperationManager 依靠设置序列化器来自动识别、解析返回的数据
- 默认使用的就是json解析,可以不用设置序列化器
- 会把json自动转换成为字典或者数组输出
1 /** 返回json数据 */ 2 - (void) getJson { 3 // 1.创建请求 管理者 4 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 5 6 // 设置序列化器 7 // [manager setResponseSerializer:[AFJSONResponseSerializer serializer]];//默认 8 9 // 2.设置参数 10 NSMutableDictionary *param = [NSMutableDictionary dictionary]; 11 param[@"type"] = @"json"; 12 13 // 3.发送请求 14 [manager GET:@"http://192.168.0.21:8080/MyTestServer/video" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) { 15 NSLog(@"请求成功"); 16 NSLog(@"返回的数据类型是:%@", [responseObject class]); 17 NSLog(@"%@", responseObject); 18 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 19 NSLog(@"请求失败"); 20 NSLog(@"%@", error); 21 }]; 22 }
2015-01-30 03:34:14.817 AFNBasicDemo[1889:192783] 返回的数据类型是:__NSCFDictionary
2015-01-30 03:34:14.818 AFNBasicDemo[1889:192783] {
videos = [
{
name = 驯龙高手1,
video = videos/1.MP4,
length = 16秒,
image = images/[20150124-180852-0].PNG
1 /** 返回xml数据 */ 2 - (void) getXml{ 3 // 1.创建请求 管理者 4 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 5 6 // 设置序列化器 7 [manager setResponseSerializer:[AFXMLParserResponseSerializer serializer]]; 8 9 // 2.设置参数 10 NSMutableDictionary *param = [NSMutableDictionary dictionary]; 11 param[@"type"] = @"xml"; 12 13 14 // 3.发送请求 15 __weak typeof(self) vc = self; 16 [manager GET:@"http://192.168.0.21:8080/MyTestServer/video" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) { 17 NSLog(@"请求成功"); 18 NSLog(@"返回的数据类型是:%@", [responseObject class]); 19 20 NSXMLParser *parser = (NSXMLParser *) responseObject; 21 parser.delegate = vc; 22 [parser parse]; 23 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 24 NSLog(@"请求失败"); 25 NSLog(@"%@", error); 26 }]; 27 }
- 也是简单发送请求
- 但是没有ASI那样的监听功能
1 - (void) downloadFile { 2 // 1.创建请求管理者 3 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 4 5 // 设置序列化器 6 [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]]; // 使用二进制数据序列化 7 8 // 3.发送请求 9 [manager GET:@"http://192.168.0.21:8080/MyTestServer/images/images.zip" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 10 11 NSLog(@"请求成功"); 12 NSLog(@"返回的数据类型是:%@", [responseObject class]); 13 14 NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 15 NSString *filePath = [cachePath stringByAppendingPathComponent:@"download.zip"]; 16 NSData *data = (NSData *) responseObject; 17 [data writeToFile:filePath atomically:YES]; 18 19 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 20 NSLog(@"请求失败"); 21 NSLog(@"%@", error); 22 }]; 23 }
- 使用POST请求,带formData的post方法
- 要区分普通参数和文件参数,把文件数据放在普通参数中上传是不行的
- 文件放在block参数中赋值
1 /** 上传文件 */ 2 - (void) uploadFile { 3 // 1.创建请求管理者 4 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 5 6 // 2.设置参数 7 NSMutableDictionary *param = [NSMutableDictionary dictionary]; 8 param[@"user"] = @"uploader"; 9 10 // 3.设置上传文件 11 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"M2.jpg" ofType:nil]; 12 NSData *fileData = [NSData dataWithContentsOfFile:filePath]; 13 14 // 4.上传文件 15 __weak typeof(fileData) uploadData = fileData; 16 17 [manager POST:@"http://192.168.0.21:8080/MyTestServer/upload" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 18 19 // 拼接文件数据 20 [formData appendPartWithFileData:uploadData name:@"uploadedFile" fileName:@"my_pic.jpg" mimeType:@"image/jpg"]; 21 22 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 23 NSLog(@"上传成功 ---- %@", responseObject); 24 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 25 NSLog(@"上传失败 ---- %@", error); 26 }]; 27 }
1 - (IBAction)monitorNetwork:(UIButton *)sender { 2 // 1.创建网络状态监控管理者 3 AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager]; 4 5 // 2.网络状态改变事件(被动检测) 6 [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 7 switch (status) { 8 case AFNetworkReachabilityStatusUnknown: 9 NSLog(@"转换为未知网络"); 10 break; 11 case AFNetworkReachabilityStatusReachableViaWWAN: 12 NSLog(@"转换为手机网络"); 13 break; 14 case AFNetworkReachabilityStatusReachableViaWiFi: 15 NSLog(@"转换为WIFI网络"); 16 break; 17 case AFNetworkReachabilityStatusNotReachable: 18 NSLog(@"转换为没有网络"); 19 break; 20 21 default: 22 break; 23 } 24 }]; 25 26 // 开启监控 27 [manager startMonitoring]; 28 29 // 主动检测 30 if ([manager isReachable]) { 31 NSLog(@"现在有网络"); 32 } else if ([manager isReachableViaWiFi]) { 33 NSLog(@"现在是通过wifi上网"); 34 } else if ([manager isReachableViaWWAN]) { 35 NSLog(@"现在是通过手机网络上网"); 36 } else { 37 NSLog(@"现在没有网络"); 38 } 39 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。