AFNetworking是一个用于iOS、macOS、watchOS和tvOS的功能强大的网络库。它构建在基础URL加载系统之上,扩展了强大的高级网络抽象,并将其构建为Cocoa。它有一个模块化的架构,设计良好,具有强大功能的api

使用 CocoaPods 引入

pod 'AFNetworking', '~> 3.0'
  • 创建一个下载任务
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];
  • 正常数据请求
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@, @, @]}; [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
/** GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 */ [[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
*/
  • 监测网络状态
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}]; [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  • SSL证书无效
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

AFNetworking 一般用法的更多相关文章

  1. AFNetworking简单用法

    GET请求 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager GET:URL parameters:ni ...

  2. AFNetWorking

    目录: 1.为什么要用AFNetworking 2.AFNetworking的用法 一.为什么要用AFNetworking 在ios开发中,一般情况下,简单的向某个web站点简单的页面提交请求并获取服 ...

  3. AJ学IOS 之微博项目实战(8)用AFNetworking和SDWebImage简单加载微博数据

    AJ分享,必须精品 一:效果 没有图文混排,也没有复杂的UI,仅仅是简单的显示出微博数据,主要介绍AFNetworking和SDWebImage的简单用法 二:加载数据AFNetworking AFN ...

  4. AFNetworking 使用总结 (用法+JSON解析)

    « AFNetworking 图片的本地缓存问题 Get application bundle seed ID in iOS » AFNetworking 使用总结 (用法+JSON解析)    Fr ...

  5. AFNetworking 用法详解

    之前一直使用ASIHttpRequest 做网络请求 ,后来新公司用AFNetWorking ,经过一段时间学习总结一下二者的优缺点: 1.AFNetWorking的优缺点 优点: 1.维护和使用者比 ...

  6. AFNetworking 使用总结 (用法+JSON解析

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

  7. AFNetworking 3.0 源码解读 总结(干货)(下)

    承接上一篇AFNetworking 3.0 源码解读 总结(干货)(上) 21.网络服务类型NSURLRequestNetworkServiceType 示例代码: typedef NS_ENUM(N ...

  8. AFNetworking 3.0 源码解读(九)之 AFNetworkActivityIndicatorManager

    让我们的APP像艺术品一样优雅,开发工程师更像是一名匠人,不仅需要精湛的技艺,而且要有一颗匠心. 前言 AFNetworkActivityIndicatorManager 是对状态栏中网络激活那个小控 ...

  9. AFNetworking 3.0 源码解读(三)之 AFURLRequestSerialization

    这篇就讲到了跟请求相关的类了 关于AFNetworking 3.0 源码解读 的文章篇幅都会很长,因为不仅仅要把代码进行详细的的解释,还会大概讲解和代码相关的知识点. 上半篇: URI编码的知识 关于 ...

随机推荐

  1. lsyncd实时同步搭建指南——取代rsync+inotify

    1. 几大实时同步工具比较 1.1 inotify + rsync 最近一直在寻求生产服务服务器上的同步替代方案,原先使用的是inotify + rsync,但随着文件数量的增大到100W+,目录下的 ...

  2. Azure Key Vault (3) 在Azure Windows VM里使用Key Vaule

    <Windows Azure Platform 系列文章目录> 本章我们介绍如何在Azure Windows VM里面,使用.NET使用Azure Key Vault 我们需要对Key V ...

  3. POJ2274(后缀数组应用)

    Long Long Message Time Limit: 4000MS   Memory Limit: 131072K Total Submissions: 25272   Accepted: 10 ...

  4. socket学习目录

    深入探析c# Socket http://www.cnblogs.com/tianzhiliang/archive/2010/09/08/1821623.html Http和Socket连接区别 ht ...

  5. Adventure Works 教程

    多维建模(Adventure Works 教程)     欢迎使用 Analysis Services 教程. 本教程通过在所有示例中使用虚构公司 Adventure Works Cycles,说明如 ...

  6. conditon_variable(条件变量)用于线程间同步

    conditon_variable(条件变量)用于线程间同步 condition_variable有5个函数,函数名及对应的功能如下: wait阻塞自己,等待唤醒 wait_for阻塞自己,等待唤醒, ...

  7. 我所理解的Restful API最佳实践

    一直在公司负责API数据接口的开发,期间也遇到了不小的坑,本篇博客算是做一个小小的记录. 1. 不要纠结于无意义的规范    在开始本文之前,我想先说这么一句:RESTful 真的很好,但它只是一种软 ...

  8. 4-1逻辑与运算符介绍 & 4-2逻辑或运算符介绍

    后面括号内的(n++)不运算了. 4-2逻辑或运算符介绍

  9. 关于weblogic 10.3.6.0 的漏洞复现(1)

    最近小R 搭建了个weblogic,  因为之前在公司找系统漏洞的时候,发现了这个漏洞,所以为了特地专门搭建了个10.3.6.0版本. 漏洞编号: CVE-2017-10271 漏洞的描述:就是web ...

  10. UVa 1658 Admiral (最小费用流)

    题意:给定一个图,求1-n的两条不相交的路线,并且权值和最小. 析:最小费用流,把每个结点都拆成两个点,中间连一条容量为1的边,然后一个作为入点,另一个是出点.最后跑两次最小费用流就行了. 代码如下: ...