EachbabyAirShipGuide 1.0.3

EachbabyAirShipGuide 1.0.3

测试(TestsTested)
语言(LangLanguage) Objective C(Obj-CObjective C)
许可证 MIT
ReleasedLast Release2016 年 9 月

gaoxiao228 维护。



 
依赖
ASIHTTPRequest~> 1.8.2
OpenUDID~> 1.0.0
MBProgressHUD~> 0.9.1
 

  • 作者
  • gao

AFNetworking

Build Status

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

然而,最重要的特性可能是使用并贡献于 AFNetworking 的开发者的惊人社区。AFNetworking 驱动了 iPhone、iPad 和 Mac 上一些最受欢迎且广受好评的应用程序。

为您的下一个项目选择 AFNetworking 或将现有项目迁移到 AFNetworking,您会为自己的决定而感到高兴!

如何开始

通讯

  • 如果您需要帮助,请使用 Stack Overflow。 (标签 'afnetworking')
  • 如果您想提出一个一般性的问题,请使用 Stack Overflow
  • 如果您发现了一个错误,且可以提供复现步骤,请提交一个问题。
  • 如果您有功能建议,请提交一个问题。
  • 如果您想做出贡献,请提交一个 pull request。

使用 CocoaPods 进行安装

CocoaPods 是一个 Objective-C 依赖关系管理器,它自动化并简化了在项目中使用第三方库(如 AFNetworking)的过程。有关更多信息,请参阅 “开始使用”指南

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项目必须支持使用现代Cocoa运行时的64位)。

在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与网络应用程序通信的常见模式,包括请求创建、响应序列化、网络可达性监控和安全性,以及请求数据管理。

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-Form 编码请求

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 对象,该对象符合 ``、``、`` 和 ``。

创建下载任务

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网络接口的域名和地址的可达性。

网络可达性是一个诊断工具,可以用来了解请求失败的原因。它不应用来判断是否发出请求。

共享网络可达性

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

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

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

尽管通常使用 AFHTTPRequestOperationManager 来发出请求是最好的方法,但也可以单独使用 AFHTTPRequestOperation

使用 AFHTTPRequestOperation 进行 GET

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 RaymondMattt Thompson 在开发 iPhone 的 Gowalla 时创建。

AFNetworking 的标志由 Alan Defibaugh 设计。

最重要的是,感谢 AFNetworking 的增加的贡献者名单

安全披露

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

许可

AFNetworking 在 MIT 许可下发布。详见 LICENSE 以获取详细信息。