A.AFN基本知识 1.概念
B.基本请求使用 1.基本使用 (1)头文件 AFNetworking.h (2)管理者类:AFHTTPRequestOperationManager (3)“GET”方法发送GET请求,使用“POST”方法发送POST请求 (4)使用字典发送参数 (5)block处理请求成功/失败
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 }
2.为了方便查看服务器返回的中文数据,给数组和字典增加一个分类,支持中文
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
3.解析返回的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 }
output: 2015-01-30 03:34:14.817 AFNBasicDemo[1889:192783] 请求成功
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 }, ... 4.解析返回的xml数据 设置使用xml序列化器,也可以自动将xml数据转换成为字典或者数组 如果不设置xml序列化器,处理返回数据会失败
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 }
C.文件下载/上传 1.文件下载
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 }
2.文件上传
(1)把文件转换成二进制数据 (2)拼接文件参数
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 }
D.网络状态监控 AFNetworkReachabilityManager (1)创建网络监控管理者 (2)设置监控网络状态变化 (3)开启监控 (4)也可以主动去获取网络状态
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 }