iOS:AFNetworking

AFNetworking是一个讨人喜欢的网络库,适用于iOS以及Mac OS X. 它构建于在NSURLConnectionNSOperation, 以及其他熟悉的Foundation技术之上. 它拥有良好的架构,丰富的api,以及模块化构建方式,使得使用起来非常轻松.例如,他可以使用很轻松的方式从一个url来得到json数据:

 

1
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/public_timeline.json"];
2
NSURLRequest *request = [NSURLRequest requestWithURL:url];
3
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
4
    NSLog(@"Public Timeline: %@", JSON);
5
} failure:nil];
6
[operation start];

 

如何开始使用

综述

CORE:

AFURLConnectionOperation:一个 NSOperation 实现了NSURLConnection 的代理方法.

HTTP Requests:

AFHTTPRequestOperation:AFURLConnectionOperation的子类,当request使用的协议为HTTP和HTTPS时,它压缩了用于决定request是否成功的状态码和内容类型.

AFJSONRequestOperation:AFHTTPRequestOperation的一个子类,用于下载和处理jason response数据.

AFXMLRequestOperation:AFHTTPRequestOperation的一个子类,用于下载和处理xml response数据.

AFPropertyListRequestOperation:AFHTTPRequestOperation的一个子类,用于下载和处理property list response数据.

HTTP CLIENT:

AFHTTPClient:捕获一个基于http协议的网络应用程序的公共交流模式.包含:

  • 使用基本的url相关路径来只做request
  • 为request自动添加设置http headers.
  • 使用http 基础证书或者OAuth来验证request
  • 为由client制作的requests管理一个NSOperationQueue
  • 从NSDictionary生成一个查询字符串或http bodies.
  • 从request中构建多部件
  • 自动的解析http response数据为相应的表现数据
  • 在网络可达性测试用监控和响应变化.

IMAGES

AFImageRequestOperation:一个AFHTTPRequestOperation的子类,用于下载和处理图片.

UIImageView+AFNetworking:添加一些方法到UIImageView中,为了从一个URL中异步加载远程图片

例子程序

XML REQUEST

 

1
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
2
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
3
  XMLParser.delegate = self;
4
  [XMLParser parse];
5
} failure:nil];
6
[operation start];

 

IMAGE REQUEST

 

1
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
2
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];

 

API CLIENT REQUEST

 

1
// AFGowallaAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
2
[[AFGowallaAPIClient sharedClient] getPath:@"/spots/9223" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
3
    NSLog(@"Name: %@", [responseObject valueForKeyPath:@"name"]);
4
    NSLog(@"Address: %@", [responseObject valueForKeyPath:@"address.street_address"]);
5
} failure:nil];

 

FILE UPLOAD WITH PROGRESS CALLBACK

 

01
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
02
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
03
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
04
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
05
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
06
}];
07
 
08
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
09
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
10
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
11
}];
12
[operation start];

 

STREAMING REQUEST

 

1
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
2
 
3
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
4
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
5
operation.outputStream = [NSOutputStream outputStreamToMemory];
6
[operation start];

 

此文章是基于AFNetworking2.5版本的,需要看AFNetworking2.0版本的请看上一篇文章:AFNetworking2.0使用

1.检测网络状态

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. + (void)netWorkStatus  
  2. {  
  3.     /** 
  4.      AFNetworkReachabilityStatusUnknown          = -1,  // 未知 
  5.      AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接 
  6.      AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱 
  7.      AFNetworkReachabilityStatusReachableViaWiFi = 2,   // WiFi 
  8.      */  
  9.     // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring  
  10.     [[AFNetworkReachabilityManager sharedManager] startMonitoring];  
  11.       
  12.     // 检测网络连接的单例,网络变化时的回调方法  
  13.     [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {  
  14.         NSLog(@"%ld", status);  
  15.     }];  
  16. }  


2.JSON方式获取数据

 

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. + (void)JSONDataWithUrl:(NSString *)url success:(void (^)(id json))success fail:(void (^)())fail;  
  2. {  
  3.     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  4.       
  5.     NSDictionary *dict = @{@"format": @"json"};  
  6.     // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情  
  7.     [manager GET:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  8.         if (success) {  
  9.             success(responseObject);  
  10.         }  
  11.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  12.         NSLog(@"%@", error);  
  13.         if (fail) {  
  14.             fail();  
  15.         }  
  16.     }];  
  17. }  


3.xml方式获取数据

 

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. + (void)XMLDataWithUrl:(NSString *)urlStr success:(void (^)(id xml))success fail:(void (^)())fail  
  2. {  
  3.     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  4.       
  5.     // 返回的数据格式是XML  
  6.     manager.responseSerializer = [AFXMLParserResponseSerializer serializer];  
  7.       
  8.     NSDictionary *dict = @{@"format": @"xml"};  
  9.       
  10.     // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情  
  11.     [manager GET:urlStr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  12.         if (success) {  
  13.             success(responseObject);  
  14.         }  
  15.           
  16.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  17.         NSLog(@"%@", error);  
  18.         if (fail) {  
  19.             fail();  
  20.         }  
  21.     }];  
  22. }  


4.post提交json数据

 

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. + (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id responseObject))success fail:(void (^)())fail  
  2. {  
  3.     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  4.     // 设置请求格式  
  5.     manager.requestSerializer = [AFJSONRequestSerializer serializer];  
  6.     // 设置返回格式  
  7.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  8.     [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  9. //        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];  
  10.         if (success) {  
  11.             success(responseObject);  
  12.         }  
  13.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  14.         NSLog(@"%@", error);  
  15.         if (fail) {  
  16.             fail();  
  17.         }  
  18.     }];  
  19.       
  20. }  


5.下载文件

 

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. + (void)sessionDownloadWithUrl:(NSString *)urlStr success:(void (^)(NSURL *fileURL))success fail:(void (^)())fail  
  2. {  
  3.     NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];  
  4.     AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];  
  5.   
  6.     NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  7.       
  8.     NSURL *url = [NSURL URLWithString:urlString];  
  9.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  10.       
  11.     NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {  
  12.         // 指定下载文件保存的路径  
  13.         //        NSLog(@"%@ %@", targetPath, response.suggestedFilename);  
  14.         // 将下载文件保存在缓存路径中  
  15.         NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];  
  16.         NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];  
  17.           
  18.         // URLWithString返回的是网络的URL,如果使用本地URL,需要注意  
  19. //        NSURL *fileURL1 = [NSURL URLWithString:path];  
  20.         NSURL *fileURL = [NSURL fileURLWithPath:path];  
  21.           
  22. //        NSLog(@"== %@ |||| %@", fileURL1, fileURL);  
  23.         if (success) {  
  24.             success(fileURL);  
  25.         }  
  26.           
  27.         return fileURL;  
  28.     } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {  
  29.         NSLog(@"%@ %@", filePath, error);  
  30.         if (fail) {  
  31.             fail();  
  32.         }  
  33.     }];  
  34.       
  35.     [task resume];  
  36. }  


6.文件上传-自定义上传文件名

 

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. + (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL fileName:(NSString *)fileName fileType:(NSString *)fileTye success:(void (^)(id responseObject))success fail:(void (^)())fail  
  2. {  
  3.     // 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理  
  4.     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  5.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  6.     //@"http://localhost/demo/upload.php"  
  7.     [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
  8.           
  9. //        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];  
  10.           
  11.         // 要上传保存在服务器中的名称  
  12.         // 使用时间来作为文件名 2014-04-30 14:20:57.png  
  13.         // 让不同的用户信息,保存在不同目录中  
  14. //        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];  
  15. //        // 设置日期格式  
  16. //        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";  
  17. //        NSString *fileName = [formatter stringFromDate:[NSDate date]];  
  18.           
  19.         //@"image/png"  
  20.         [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:fileTye error:NULL];  
  21.           
  22.     } success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  23.         if (success) {  
  24.             success(responseObject);  
  25.         }  
  26.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  27.         if (fail) {  
  28.             fail();  
  29.         }  
  30.     }];  
  31. }  


7.文件上传-随机生成文件名

 

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
    1. + (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL success:(void (^)(id responseObject))success fail:(void (^)())fail  
    2. {  
    3.     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
    4.     // AFHTTPResponseSerializer就是正常的HTTP请求响应结果:NSData  
    5.     // 当请求的返回数据不是JSON,XML,PList,UIImage之外,使用AFHTTPResponseSerializer  
    6.     // 例如返回一个html,text...  
    7.     //  
    8.     // 实际上就是AFN没有对响应数据做任何处理的情况  
    9.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
    10.       
    11.     // formData是遵守了AFMultipartFormData的对象  
    12.     [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
    13.           
    14.         // 将本地的文件上传至服务器  
    15. //        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];  
    16.           
    17.         [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];  
    18.     } success:^(AFHTTPRequestOperation *operation, id responseObject) {  
    19. //        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];  
    20. //          
    21. //        NSLog(@"完成 %@", result);  
    22.         if (success) {  
    23.             success(responseObject);  
    24.         }  
    25.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
    26.         NSLog(@"错误 %@", error.localizedDescription);  
    27.         if (fail) {  
    28.             fail();  
    29.         }  
    30.     }];  
    31. }  

转载于:https://www.cnblogs.com/LJson/p/4380430.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值