CGT_Pod_ObjC 1.3

CGT_Pod_ObjC 1.3

测试已测试
语言语言 Obj-CObjective-C
许可 MIT
发布最新发布2016年5月

Rahul Bansal 维护。



 
依赖
AFNetworking~> 2.5
MBProgressHUD>= 0
Reachability>= 0
Mantle~> 2.0
SDWebImage~> 3.7
BFKit>= 0
 

  • Rahul Bansal

AFNetworking 是一个令人愉快的 iOS 和 Mac OS X 网络库。它基于 Foundation URL 加载系统,扩展了 Cocoa 内置的强大高级网络抽象。它具有模块化架构,API 设计出色,功能丰富,使用愉快。

然而,最重要的特性可能是,每天使用和贡献 AFNetworking 的开发者群体令人难以置信。AFNetworking 支持了 iPhone,iPad 和 Mac 上一些最受欢迎和备受好评的应用。

选择 AFNetworking 用于您的下一个项目,或将现有项目迁移过来——您会为此而感到高兴的!

如何开始

沟通

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

Podfile

platform :ios, '7.0'
pod "AFNetworking", "~> 2.0"

要求

AFNetworking 版本 最小 iOS 目标 最小 OS X 目标 注释
2.x 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项目必须支持64位和现代Cocoa运行时)。

用Swift进行编程?尝试使用Alamofire,以获得更传统的API集合。

架构

NSURLConnection

  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

NSURLSession (iOS 7 / Mac OS X 10.9)

  • AFURLSessionManager
  • AFHTTPSessionManager

序列化

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

附加功能

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

用法

HTTP 请求操作管理器

AFHTTPRequestOperationManager 封装了通过HTTP与Web应用通信的常见模式,包括请求创建、响应序列化、网络可达性监控和安全,以及请求操作管理。

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);
}];

POST URL编码表单请求

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 根据指定的 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]];
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 error:nil];
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监视WWAN和WiFi网络接口的域和地址的可达性。

  • 不要使用可达性判断原始请求是否应该发送。
    • 你应该尝试发送它。
  • 你可以使用可达性来判断何时应该自动重试请求。
    • 尽管它可能仍然失败,但连接可用性的可达性通知是一个重试的好时机。
  • 网络可达性是确定请求可能失败原因的有用工具。
    • 在网络请求失败后,告诉用户他们离线比提供一个更技术但更准确的错误,例如“请求超时”,要好。

另请参阅WWDC 2012会议706,“网络最佳实践”。

共享网络可达性

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

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

HTTP管理器可达性

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;
    }
}];

[manager.reachabilityManager startMonitoring];

安全策略

AFSecurityPolicy在安全连接中,根据固定的X.509证书和公钥评估服务器信任。

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

允许无效的SSL证书

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

AFHTTPRequestOperation

AFHTTPRequestOperationAFURLConnectionOperation的子类,用于使用HTTP或HTTPS协议的请求。它封装了可接受的状态码和内容类型的概念,这些标志决定了请求的成功或失败。

尽管使用AFHTTPRequestOperationManager通常是处理请求的最佳方式,但也可以单独使用AFHTTPRequestOperation

GETAFHTTPRequestOperation

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在Tests子目录中包含了一系列单元测试。为了运行单元测试,您必须通过CocoaPods安装测试依赖项。

$ cd Tests
$ pod install

安装测试依赖项后,您可以通过Xcode中的“iOS Tests”和“OS X Tests”方案执行测试套件。

从命令行运行测试

测试也可以从命令行或在持续集成环境中运行。在从命令行运行测试之前,需要安装xcpretty实用程序。

$ gem install xcpretty

安装xcpretty后,您可以通过执行rake test来执行套件。

鸣谢

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

AFNetworking最初由Scott Raymond(https://github.com/sco/)和Mattt Thompson(https://github.com/mattt/)在开发iPhone版本的Gowalla(https://en.wikipedia.org/wiki/Gowalla)时创建。

AFNetworking的标志由Alan Defibaugh(http://www.alandefibaugh.com/)设计。

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

安全披露

如果您认为您发现了AFNetworking的安全漏洞,请尽快通过电子邮件报告,电子邮件地址为[email protected]。请不要将其发布到公共问题跟踪器。

版权协议

AFNetworking是在MIT许可下发布的。有关详细信息,请参阅LICENSE文件。