iOS网络编程 (第三方开源库)----->AFNetworking

AFNetworking是一个为 iOS 和 Mac OSX 制作的令人愉快的网络库,它建立在URL 装载系统框架的顶层,内置在Cocoa里,扩展了强有力的高级网络抽象。它的模块架构被良好的设计,拥有丰富的功能,因此,使用起来,必定赏心悦目。

       @原文链接https://github.com/AFNetworking/AFNetworking,我在此基础上了点配置修改

       @介绍

  1.支持HTTP请求和基于REST的网络服务(包括GET、POST、 PUT、DELETE等)
  2.支持ARC
  3.要求iOS 5.0及以上版本

  4.UIKit扩展


       @配置

       1.下载AFNetworking,将2个文件夹:AFNetworking和UIKit+AFNetworking拖入工程

       2.导入以下库文件:CFNetwork、Security、SystemConfiguration、MobileCoreServices

       3.如果你以前用的是1.0版本,那么AFNetworking 2.0 Migration Guide能帮助你

       4.如果你是用CocoaPods配置的,那么

           platform:ios,'7.0'

           pod"AFNetworking","~>2.0"


           @使用

           1.HTTP请求操作

           AFHTTPRequestOperationManager封装的共同模式与web应用程序通过HTTP通信,包括创建请求,响应序列化,网络可达性监控、运营管理和安全,以及请求。

           *GET请求

[objc]  view plain copy
  1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  2. [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  3.     NSLog(@"JSON: %@", responseObject);  
  4. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  5.     NSLog(@"Error: %@", error);  
  6. }];  

            *POST请求

[objc]  view plain copy
  1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  2. NSDictionary *parameters = @{@"foo"@"bar"};  
  3. [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  4.     NSLog(@"JSON: %@", responseObject);  
  5. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  6.     NSLog(@"Error: %@", error);  
  7. }];  
            *POST请求(多表)

[objc]  view plain copy
  1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
  2. NSDictionary *parameters = @{@"foo"@"bar"};  
  3. NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];  
  4. [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
  5.     [formData appendPartWithFileURL:filePath name:@"image" error:nil];  
  6. } success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  7.     NSLog(@"Success: %@", responseObject);  
  8. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  9.     NSLog(@"Error: %@", error);  
  10. }];  
             

             2.AFURLSessionManager(NSURLSession详细见网络编程(6))

             创建和管理制定的NSURLSession对象NSURLSessionConfiguration对象必须实现<NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, <NSURLSessionDelegate>协议

              *创建一个下载任务

[objc]  view plain copy
  1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  
  2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];  
  3.   
  4. NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];  
  5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];  
  6.   
  7. NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {  
  8.     NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];  
  9.     return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];  
  10. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {  
  11.     NSLog(@"File downloaded to: %@", filePath);  
  12. }];  
  13. [downloadTask resume];  
                 *创建一个上传任务

[objc]  view plain copy
  1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  
  2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];  
  3.   
  4. NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];  
  5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];  
  6.   
  7. NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];  
  8. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {  
  9.     if (error) {  
  10.         NSLog(@"Error: %@", error);  
  11.     } else {  
  12.         NSLog(@"Success: %@ %@", response, responseObject);  
  13.     }  
  14. }];  
  15. [uploadTask resume];  
              *创建一个带多表,进度的上传任务

[objc]  view plain copy
  1. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
  2.         [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];  
  3.     } error:nil];  
  4.   
  5. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];  
  6. NSProgress *progress = nil;  
  7.   
  8. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {  
  9.     if (error) {  
  10.         NSLog(@"Error: %@", error);  
  11.     } else {  
  12.         NSLog(@"%@ %@", response, responseObject);  
  13.     }  
  14. }];  
  15.   
  16. [uploadTask resume];  
               *创建一个数据流Data任务

[objc]  view plain copy
  1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  
  2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];  
  3.   
  4. NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];  
  5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];  
  6.   
  7. NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {  
  8.     if (error) {  
  9.         NSLog(@"Error: %@", error);  
  10.     } else {  
  11.         NSLog(@"%@ %@", response, responseObject);  
  12.     }  
  13. }];  
  14. [dataTask resume];  
              

                3.网络监测(一般会用另一个网络监测类,Reachability,还有JSON解析方法,反正我也一般不用,自行脑补)

                AFNetworkReachabilityManager监控网络领域的可达性,WWAN地址和WiFi接口.

                *当前网络状态

[objc]  view plain copy
  1. [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {  
  2.     NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));  
  3. }];  

                             *HTTP Manager 可达性

[objc]  view plain copy
  1. NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];  
  2. AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];  
  3.   
  4. NSOperationQueue *operationQueue = manager.operationQueue;  
  5. [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {  
  6.     switch (status) {  
  7.         case AFNetworkReachabilityStatusReachableViaWWAN:  
  8.         case AFNetworkReachabilityStatusReachableViaWiFi:  
  9.             [operationQueue setSuspended:NO];  
  10.             break;  
  11.         case AFNetworkReachabilityStatusNotReachable:  
  12.         default:  
  13.             [operationQueue setSuspended:YES];  
  14.             break;  
  15.     }  
  16. }];  
                       

                  4.AFHTTPRequestOperation

                  AFHTTPRequestOperation是使用HTTP或HTTPS协议的AFURLConnectionOperation的子类。
它封装的获取后的HTTP状态和类型将决定请求的成功与否。虽然AFHTTPRequestOperationManager通常是最好的去请求的方式,但是AFHTTPRequestOpersion也能够单独使用。

                               *GET请求

[objc]  view plain copy
  1. NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];  
  2. NSURLRequest *request = [NSURLRequest requestWithURL:URL];  
  3. AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];  
  4. op.responseSerializer = [AFJSONResponseSerializer serializer];  
  5. [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  
  6.     NSLog(@"JSON: %@", responseObject);  
  7. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  8.     NSLog(@"Error: %@", error);  
  9. }];  
  10. [[NSOperationQueue mainQueue] addOperation:op];  
 
                              *批量多请求

[objc]  view plain copy
  1. NSMutableArray *mutableOperations = [NSMutableArray array];  
  2. for (NSURL *fileURL in filesToUpload) {  
  3.     NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
  4.         [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];  
  5.     }];  
  6.   
  7.     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];  
  8.   
  9.     [mutableOperations addObject:operation];  
  10. }  
  11.   
  12. NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {  
  13.     NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);  
  14. } completionBlock:^(NSArray *operations) {  
  15.     NSLog(@"All operations in batch complete");  
  16. }];  
  17. [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];  


         @其他资料

                 1.官网

                 2.英文文档


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值