ProjectLibrary 1.0.6

ProjectLibrary 1.0.6

测试已测试
语言语言 Obj-CObjective C
许可证 MIT
发布最后发布2016年11月

1273011249维护。



  • 作者:
  • xuyong

AFNetworking是一个出色的iOS和Mac OS X网络库。它是基于Foundation URL 加载系统构建的,扩展了Cocoa中内置的高级网络抽象化。它具有模块化架构,具有精心设计的、功能丰富的API,使用起来非常愉悦。

然而,最重要的功能可能是每天使用并贡献于AFNetworking的开发者群体。AFNetworking支持iPhone、iPad和Mac上的一些最受欢迎和评价最高的应用程序。

选择AFNetworking作为您的下一个项目,或者将现有项目迁移过来——您会知道这是正确的选择!

如何开始

交流

  • 如果您需要帮助,请使用Stack Overflow。(标签为'afnetworking')
  • 如果您想问一个一般的问题,请使用Stack Overflow
  • 如果您发现了一个并且可以提供可靠地重现其步骤的bug,请打开一个问题。
  • 如果您有一个功能请求,请打开一个问题。
  • 如果您想贡献,请提交一个拉取请求。

安装

AFNetworking支持多种方法在项目中安装库。

Podfile

要使用CocoaPods将AFNetworking集成到您的Xcode项目中,请在您的Podfile中指定它。

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

pod 'AFNetworking', '~> 3.0'

然后,运行以下命令

$ pod install

要求

AFNetworking版本 最低iOS目标 最低OS X目标 最低watchOS目标 最低tvOS目标 注释
3.x iOS 7 OS X 10.9 watchOS 2.0 tvOS 9.0 需要Xcode 7及以上版本。已移除对NSURLConnectionOperation的支持。
2.6 -> 2.6.3 iOS 7 OS X 10.9 watchOS 2.0 不适用 需要Xcode 7及以上版本。
2.0 -> 2.5.4 iOS 6 OS X 10.8 不适用 不适用 需要Xcode 5及以上版本。NSURLSession子规范需要iOS 7或OS X 10.9。
1.x iOS 5 Mac OS X 10.7 不适用 不适用
0.10.x iOS 4 Mac OS X 10.6 不适用 不适用

(OS X项目必须支持使用现代Cocoa运行时环境的64位)。

用Swift编程?请尝试使用Alamofire,它提供了更传统的API集。

架构

NSURLSession

  • AFURLSessionManager
  • AFHTTPSessionManager

序列化

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

附加功能

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

使用

AFURLSessionManager

AFURLSessionManager根据指定的NSURLSessionConfiguration对象创建并管理一个NSURLSession对象,该对象符合<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 *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL 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]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable 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://httpbin.org/get"];
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 error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL表单参数编码

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
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 error:nil];
POST http://example.com/
Content-Type: application/json

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

网络可达性管理器

AFNetworkReachabilityManager监视WAN和WiFi网络接口的域名和地址的可达性。

  • 不要使用可达性来确定是否应该发送原始请求。
    • 你应该尝试发送。
  • 您可以使用可达性(Reachability)来确定何时应该自动重试请求。
    • 尽管它可能依然会失败,但一旦收到可达性通知表示联网可用,这就是重试的好时机。
  • 网络可达性是确定请求为何失败的有用工具。
    • 网络请求失败后,告知用户离线状态比给出一个更技术化但准确的错误,如“请求超时”,更佳。

请参阅WWDC 2012 讲座 706,"网络最佳实践"。

共享网络可达性

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

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

安全策略

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

将固定的SSL证书添加到你的应用中可以帮助防止中间人攻击和其他漏洞。用于处理敏感客户数据或财务信息的应用程序强烈建议通过配置和启用SSL固定的HTTPS连接路由所有通信。

允许无效SSL证书

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

单元测试

AFNetworking在Tests子目录包含一系列单元测试。只需在希望测试的平台框架上执行测试操作即可运行这些测试。

致谢

AFNetworking 由 Alamofire 软件基金会 拥有和维护。

AFNetworking最初由 Scott RaymondMattt Thompson 在开发iPhone上的 Golfalla 应用中创建。

AFNetworking的标志由 Alan Defibaugh 设计。

最重要的是,感谢AFNetworking不断增长的贡献者名单

安全披露

如果你认为你发现了AFNetworking中的一个安全漏洞,你应该尽快通过邮件报告,请发邮件至 [email protected]。请勿将其发布到公共问题跟踪器。

许可协议

AFNetworking遵循MIT许可协议。请参阅LICENSE文件获取详细信息。