第三方开源库 AFNetworking

原创 2015年07月08日 17:36:13
Tag标签:网络编程  第三方  
  • 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请求

     

    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请求

     

    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请求(多表)

     

     

    01.AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    02.NSDictionary *parameters = @{@"foo": @"bar"};
    03.NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    04.[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    05.[formData appendPartWithFileURL:filePath name:@"image" error:nil];
    06.} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    07.NSLog(@"Success: %@", responseObject);
    08.} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    09.NSLog(@"Error: %@", error);
    10.}];

     

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

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

    *创建一个下载任务

     

    01.NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    02.AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    03. 
    04.NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
    05.NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    06. 
    07.NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    08.NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    09.return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    10.} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    11.NSLog(@"File downloaded to: %@", filePath);
    12.}];
    13.[downloadTask resume];
    *创建一个上传任务

     

     

    01.NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    02.AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    03. 
    04.NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    05.NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    06. 
    07.NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    08.NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    09.if (error) {
    10.NSLog(@"Error: %@", error);
    11.else {
    12.NSLog(@"Success: %@ %@", response, responseObject);
    13.}
    14.}];
    15.[uploadTask resume];
    *创建一个带多表,进度的上传任务

     

     

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

     

     

    01.NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    02.AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    03. 
    04.NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    05.NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    06. 
    07.NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    08.if (error) {
    09.NSLog(@"Error: %@", error);
    10.else {
    11.NSLog(@"%@ %@", response, responseObject);
    12.}
    13.}];
    14.[dataTask resume];

     

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

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

    *当前网络状态

     

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

    *HTTP Manager 可达性

     

     

    01.NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
    02.AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    03. 
    04.NSOperationQueue *operationQueue = manager.operationQueue;
    05.[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    06.switch (status) {
    07.case AFNetworkReachabilityStatusReachableViaWWAN:
    08.case AFNetworkReachabilityStatusReachableViaWiFi:
    09.[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请求

     

    01.NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
    02.NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    03.AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    04.op.responseSerializer = [AFJSONResponseSerializer serializer];
    05.[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    06.NSLog(@"JSON: %@", responseObject);
    07.} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    08.NSLog(@"Error: %@", error);
    09.}];
    10.[[NSOperationQueue mainQueue] addOperation:op];

    *批量多请求

     

     

    01.NSMutableArray *mutableOperations = [NSMutableArray array];
    02.for (NSURL *fileURL in filesToUpload) {
    03.NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    04.[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
    05.}];
    06. 
    07.AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    08. 
    09.[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];

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

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

AFNetworking是一个为 iOS 和 Mac OSX 制作的令人愉快的网络库,它建立在URL 装载系统框架的顶层,内置在Cocoa里,扩展了强有力的高级网络抽象。它的模块架构被良好的设计,...

xlistview第三方开源库

  • 2016年11月16日 13:37
  • 440KB
  • 下载

Android5.1.+ getRunningAppProcesses()获取运行中进程(第三方开源库)

google可能为了安全考虑,在5.1.+后调用activitymanager.getRunningAppProcesses()方法只能返回你自己应用的进程,那如何在5.1.+后获取运行中进程呢?一个...

第三方开源库的简单再封装

  • 2016年07月06日 10:37
  • 13KB
  • 下载

第三方开源库:图片选择MultiImageSelector

MultiImageSelector github地址:https://github.com/lovetuzitong/MultiImageSelector 模仿微信图片选择,返回的是图片的...

KNX协议第三方开源库

  • 2015年03月09日 14:58
  • 1.43MB
  • 下载

AsyncSocket第三方开源库经常会在release环境下出现接收消息闪退

原文链接:http://blog.csdn.net/small_tgs/article/details/50826454#comments 自从Xcode7出来以后,项目中使用的AsyncSoc...

Android Studio 导入 jar 包和第三方开源库的方法

Android Studio是Google为Android开发提供的原生的开发环境。相比较之前的Eclipse真的是强大到不行。在项目构建中,Android是采用Gradle进行构建的。开发过程中,我...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:第三方开源库 AFNetworking
举报原因:
原因补充:

(最多只允许输入30个字)