Usage
HTTP Request Operation Manager AFHTTPRequestOperationManager encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
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 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 creates and manages an NSURLSession object based on a specifiedNSURLSessionConfiguration object, which conforms to <NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, and <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": @[@, @, @]}; 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 [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/
Content-Type: application/x-www-form-urlencoded foo=bar&baz[]=&baz[]=&baz[]= JSON Parameter Encoding [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/
Content-Type: application/json {"foo": "bar", "baz": [,,]} Network Reachability Manager AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. Network reachability is a diagnostic tool that can be used to understand why a request might have failed. It should not be used to determine whether or not to make a request.
Shared Network Reachability [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}]; HTTP Manager Reachability 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 evaluates server trust against pinned X. certificates and public keys over secure connections. Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
Allowing Invalid SSL Certificates AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production AFHTTPRequestOperation AFHTTPRequestOperation is a subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. Although AFHTTPRequestOperationManager is usually the best way to go about making requests,AFHTTPRequestOperation can be used by itself.
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]; Batch of Operations 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];

afnetwork使用的更多相关文章

  1. AFNetwork ATS 网络层改造

    最近一直做项目的ATS改造,期间遇到了种种问题,各种坑都记录下来, 比如iOS版本.afnetwork版本.证书(是否为自签证书).域名验证.TLS版本等等,我们项目更复杂,还使用了域名到IP映射的路 ...

  2. iOS开发之网络编程--1、AFNetwork 3.x 的所有开发中常用基础介绍

    前言:第三方网络请求框架中AFNetwork 3.x收欢迎程度相当高的: 由于iOS 7 和 Mac OS X 10.9 Mavericks 中一个显著的变化就是对 Foundation URL 加载 ...

  3. AFNetwork作用和用法详解

    AFNetwork是一个轻量级的网络请求api类库.是以NSURLConnection, NSOperation和其他方法为基础的. 下面这个例子是用来处理json请求的:NSURL *url = [ ...

  4. AFNetwork学习(二)——GET/POST请求

    为了学习AFNetwork,自己搭建整理了一下AFNetwork向后台发送请求和后台返回json数据的整个处理过程.利用Struts2搭建了一个后台,提供Action并返回json数据 环境:Xcod ...

  5. 第10月第20天 afnetwork like MKNetworkEngine http post

    1. + (AFHTTPRequestOperation *)requestSellerWithCompletion:(requestFinishedCompletionBlock)successBl ...

  6. AFNetwork源码解析

    1.关于AFRequestSerializer: 这里分好几个部分,我们首先从NSMutableRequest的相关方法来出发: 比如我们要上传一个文件,那么需要些很麻烦的请求体: HTTP请求头我们 ...

  7. AFNetwork 作用和用法详解

    转自:http://www.cnblogs.com/mkai/p/5729685.html AFNetworking是一个轻量级的iOS网络通信类库.它建立在NSURLConnection和NSOpe ...

  8. AFNetwork 作用和使用方法具体解释

    转自:http://www.maxiaoguo.com/clothes/269.html AFNetworking是一个轻量级的iOS网络通信类库.它建立在NSURLConnection和NSOper ...

  9. AFNetWork 简单实用demo

    NSString *postUrl = @"http://www.huway.com/api_index?module=event&action=topads"; NSDi ...

  10. 转-AFNetwork 作用和用法详解

    来自:http://www.maxiaoguo.com/clothes/269.html AFNetworking是一个轻量级的iOS网络通信类库.它建立在NSURLConnection和NSOper ...

随机推荐

  1. [转][读书笔记]深入理解java虚拟机

    原文地址:http://blog.csdn.net/hanekawa/article/details/51972259 第二章 Java内存区域与内存溢出异常 一,运行时数据区域: 1.        ...

  2. [Linux] 使用mount来挂载设备到目录

    一般情况下直接mount 设备路径 目录路径,就可以了.umount 设备名,就可以卸载这个设备了使用lsblk -f可以查看挂载的设备,以及这些设备的文件系统. root@tao-PC:/boot# ...

  3. Shell命令-搜索文件或目录之which、find

    文件及内容处理 - which.find 1. which:查找二进制命令,按环境变量PATH路径查找 which命令的功能说明 which 命令用于查找文件.which 指令会在环境变量 $PATH ...

  4. C++ 基础语法 快速复习笔记---面对对象编程(2)

    1.C++面对对象编程: a.定义: 类定义是以关键字 class 开头,后跟类的名称.类的主体是包含在一对花括号中.类定义后必须跟着一个分号或一个声明列表. 关键字 public 确定了类成员的访问 ...

  5. vue项目关闭eslint校验

    [前言] eslint是一个JavaScript的校验插件,通常用来校验语法或代码的书写风格.这篇文章主要介绍了vue项目关闭eslint校验,需要的朋友可以参考下 [主体] 简介eslint esl ...

  6. 好用的代码统计小工具SourceCounter(下载)

    SourceCounter下载链接 https://pan.baidu.com/s/12Cg51L0hRn5w-m1NQJ-Xlg 提取码:i1cd 很多时候我们需要统计自己所写的代码的数量.举个栗子 ...

  7. OC方法交换swizzle详细介绍——不再有盲点

    原文链接:https://www.cnblogs.com/mddblog/p/11105450.html 如果对方法交换已经比较熟悉,可以跳过整体介绍,直接看常见问题部分 整体介绍 方法交换是runt ...

  8. 判断101-200之间有多少个素数,并输出所有素数,方法:用一个数分别去除2到sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数。

    <?php$sum=0;for($i=101;$i<=200;$i++){    for($j=2;$j<=sqrt($i);$j++)    {       if($i%$j==0 ...

  9. (day51)三、ORM、路由层、版本差异、流程图

    目录 一.ORM关系建立 (一)ForeignKey(一对多) (二)ManyToManyField(多对多) (三)OneToOneField(一对一) 二.django请求生命周期流程图 三.ur ...

  10. Docker 简单发布dotnet core项目 文本版

    原文:https://www.cnblogs.com/chuankang/p/9474591.html docker发布dotnet core简单流程 照着步骤来基本没错 但是有几个要注意的地方: v ...