AFNetworking

谷歌翻译

AFNetworking是为iOSMac OS X。它是建立在之上的愉快的网络库基金会的URL加载系统 ,延长内置到可可的功能强大的高级网络抽象。 它有一个模块化的架构,设计精良,功能丰富的API,是一个欢乐的使用。

也许,最重要的功能,但是,是谁使用,每天贡献AFNetworking开发商惊人的社群。 AFNetworking一些权力在iPhoneiPadMac的最流行和广受好评的应用程序。

选择AFNetworking你的下一个项目,或迁移在你现有的项目 -你很高兴你没有!

如何开始

安装与CocoaPods

CocoaPods是一个依赖经理的Objective-C,它能够自动并简化使用像AFNetworking的第三方库在项目的进程。 请参阅入门指南获取更多信息 

Podfile

  平台IOS‘7 .0‘

 “AFNetworking”> 2.0”

2.0

AFNetworking 2.0是一个重大更新的框架。 建设2年的发展,这个新版本引入了强大的新功能,同时提供了一个简单的升级路径,为现有的用户。

阅读AFNetworking 2.0迁移指南为建筑和API的变化的概述。

最新消息

  • 重构架构
  • 支持NSURLSession
  • 序列化模块
  • 扩大的UIKit扩展
  • 实时功能与火箭

要求

AFNetworking 2.0和更高要求的Xcode 5,确定目标的的iOS 6.0及以上版本,或Mac OS 10.8山狮( 64位与现代可可运行时 )及以上。

对于与iOS 5Mac OS X 10.7的兼容性,请使用最新的1.x的版本 

对于与iOS 4.3Mac OS X 10.6的兼容性,请使用最新的0.10.x版本 

建筑

NSURLConnection

  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

NSURLSessioniOS7 / Mac OS X10.9

  • AFURLSessionManager
  • AFHTTPSessionManager

序列化

  • <AFURLRequestSerialization>
    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer
  • <AFURLResponseSerialization>
    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer Mac OS X中)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

附加功能

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

用法

HTTP请求营运经理

AFHTTPRequestOperationManager封装与Web应用程序进行通信通过HTTP,包括要求制作,响应序列化,网络可达性监控和安全性,以及要求经营管理的常见模式。

GET请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError*error) {
    NSLog(@"Error: %@", error);
}];

POSTURL格式编码的请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo":@"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation*operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError*error) {
    NSLog(@"Error: %@", error);
}];


POST多部分请求

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



AFURLSessionManager

AFURLSessionManager创建和管理一个NSURLSession根据指定的对象NSURLSessionConfiguration对象,这符合<NSURLSessionTaskDelegate>  <NSURLSessionDataDelegate>  <NSURLSessionDownloadDelegate><NSURLSessionDelegate> 

创建下载任务

 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL*(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) firstObject]];
    return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL*filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

创建上传任务

  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse*response, id responseObject, NSError*error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];


创建上传任务的多部分请求,与进展

   

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse*response, id responseObject, NSError*error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
        }
    }];

    [uploadTask resume];

创建数据任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse*response, id responseObject, NSError*error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

请求序列化

请求序列化创建URL字符串,编码参数作为一个查询字符串或HTTP主体请求。

NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo":@"bar", @"baz": @[@1,@2, @3]};

查询字符串参数编码

 [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL,表单参数编码

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3

JSON编码参数

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

网络可达性管理

AFNetworkReachabilityManager监控领域的可达性,并为WWANWiFi网络接口的地址。

共享网络可达性

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

与基本URLHTTP经理

baseURL提供,网络可达性的作用范围是该基地URL的主机。

  NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue setSuspended:NO];
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            [operationQueue setSuspended:YES];
            break;
    }
}];

安全策略

AFSecurityPolicy评估对固定X.509证书和通过安全连接的公共密钥服务器信任。

新增固定SSL证书到你的应用有助于防止人在这方面的中间人攻击和其他安全漏洞。 应用程序处理敏感的客户数据或财务信息我们强烈建议路线在使用SSL钉扎配置和启用HTTPS连接的所有通信。

使无效的SSL证书

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates =YES; // 不建议在生产

AFHTTPRequestOperation

AFHTTPRequestOperation是的一个子类AFURLConnectionOperation使用HTTPHTTPS协议请求。 它封装的接受状态代码和内容类型,这决定了请求的成功或失败的概念。

虽然AFHTTPRequestOperationManager通常是去提出要求的最佳途径, AFHTTPRequestOperation可以单独使用。

GET with AFHTTPRequestOperation

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

操作的批处理

 

NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [mutableOperations addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

单元测试

AFNetworking包括一套内部的测试子目录中的单元测试。 为了运行单元测试,你必须通过CocoaPods安装测试的依赖关系:

 $ cd Tests

 $ pod install 

一旦测试的依赖安装,你可以通过在XcodeiOS测试”OS X的测试计划,执行测试套件。

使用xctool

测试也可以通过命令行或在一个持续集成环境中运行xctool ,它可以安装自制软件 

 $ brew update 

 $ brew install xctool --HEAD 

一旦xctool安装,你可以通过执行该套件rake test 

AFNetworking

上一篇:DIV + CSS 布局入门


下一篇:MIT 6.S081 操作系统 LAB6:Copy-on-Write