ANF使用经验总结

简介: <h3 style="padding:0px; margin:1em 0px 16px; line-height:1.43; font-size:1.5em; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,'Segoe UI',Arial,freesans,sans-serif"> HTTP Request Ope

HTTP Request Operation Manager

AFHTTPRequestOperationManager封装的共同模式与web应用程序通过HTTP通信,包括创建请求,响应序列化,网络可达性监控、运营管理和安全,以及请求。

GET Request

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-Encoded Request  {  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 Multi-Part Request  {多声部的请求}

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对象基于specifiedNSURLSessionConfiguration对象,这符合< NSURLSessionTaskDelegate >、< NSURLSessionDataDelegate >、< NSURLSessionDownloadDelegate >,< NSURLSessionDelegate >。

Creating a Download Task     { 创建一个下载任务 }

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

Creating an Upload Task   {创建一个上传的任务 }

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

Creating an Upload Task for a Multi-Part Request, with Progress

            { 创建一个多部分请求上传任务,进步  }

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

Creating a Data Task     {创建一个数据的任务}

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

Request Serialization    {请求序列化}

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

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

Query String Parameter Encoding     {查询字符串参数编码}

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

URL Form Parameter Encoding    {   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 Parameter Encoding    {JSON参数编码}

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

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

Network Reachability Manager    {网络可达性管理器}

AFNetworkReachabilityManager监控领域的可达性,和地址WWAN和无线网络接口。

Shared Network Reachability     {共享的网络可达性}

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

HTTP Manager Reachability   {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];

Security Policy    {安全策略}

  AFSecurityPolicy评估对固定X服务器信任。509证书和公钥安全连接。

  

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

Allowing Invalid SSL Certificates   {使无效的SSL证书}

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

AFHTTPRequestOperation

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

  

  尽管AFHTTPRequestOperationManager通常是最佳的方法发出请求,可以使用AFHTTPRequestOperation本身。

GET with AFHTTPRequestOperation    {得到与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];

Batch of Operations   {批处理操作}

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

目录
相关文章
|
编译器 C++
C++模板之——类模板详解及代码示例
C++模板之——类模板详解及代码示例
C++模板之——类模板详解及代码示例
|
机器学习/深度学习 存储 PyTorch
PyTorch自定义学习率调度器实现指南
本文将详细介绍如何通过扩展PyTorch的 ``` LRScheduler ``` 类来实现一个具有预热阶段的余弦衰减调度器。我们将分五个关键步骤来完成这个过程。
639 2
`cmd`模块是Python标准库中的一个模块,它提供了一个简单的框架来创建命令行解释器。
`cmd`模块是Python标准库中的一个模块,它提供了一个简单的框架来创建命令行解释器。
|
12月前
|
数据采集 存储 JavaScript
Dynamic Website 爬虫:应对动态内容与 JavaScript 渲染挑战
本文深入探讨了如何设计针对动态网站的爬虫,以采集 WIPO Brand Database 中的专利和技术信息。文章详细介绍了动态网站的挑战,包括 JavaScript 渲染、反爬虫机制和异步加载,并提出了解决方案,如使用 Selenium 模拟浏览器、代理 IP 技术和 API 抓取。最后,通过具体代码示例展示了如何实现这些技术手段。
639 0
|
机器学习/深度学习 自然语言处理 算法
Python遗传算法GA对长短期记忆LSTM深度学习模型超参数调优分析司机数据|附数据代码
Python遗传算法GA对长短期记忆LSTM深度学习模型超参数调优分析司机数据|附数据代码
|
存储 数据可视化 PyTorch
Transformers 4.37 中文文档(十四)(1)
Transformers 4.37 中文文档(十四)
319 1
|
SQL 存储 数据处理
数据库技术:核心原理、应用场景与未来趋势
一、引言 数据库技术作为现代信息科技的重要支柱,为企业和组织提供了稳定、高效的数据管理手段
2137 0
|
安全 Swift iOS开发
【Swift开发专栏】Swift基础语法详解
【4月更文挑战第30天】Swift是苹果2014年发布的编程语言,适用于iOS、macOS等多个平台。它比Objective-C更安全、现代、易学。本文主要介绍Swift基础:常量变量(`let`和`var`),数据类型(整数、浮点数、布尔、字符串),元组,可选类型(Optional)。此外,还涉及运算符(算术、比较、逻辑)、控制流(`if`、`for`、`while`、`switch`)以及函数和闭包的使用。通过这些基础知识的学习,可以帮助初学者快速上手Swift。
282 1
|
Java 编译器 数据安全/隐私保护
Java语言包(Package)深入解析
Java语言包(Package)深入解析
371 0
|
测试技术 程序员 图形学
常用的Negative prompt用语-测试模型(Stable-Diffusion)
常用的Negative prompt用语-测试模型(Stable-Diffusion)
474 0