1、使用AFNetwoking
//导入
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
//和导入系统框架 MobileCoreServices、SystemConfiguration、sec 。。忽略
网络监听
AFNetworkReachabilityManager 网络监听管理者对象
方法:
设置监听
setReachabilityStatusChangeBlock
启动监听
startMonitoring
代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//创建网络监听管理者对象 AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
/* typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,//未识别的网络
AFNetworkReachabilityStatusNotReachable = 0,//不可达的网络(未连接)
AFNetworkReachabilityStatusReachableViaWWAN = 1,//2G,3G,4G...
AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi网络 }; */
//设置监听
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未识别的网络");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"不可达的网络(未连接)");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"2G,3G,4G...的网络");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi的网络");
break;
default:
break;
}
}];
//开始监听
[manager startMonitoring];}
下载
//
NSURLSessionConfiguration
> + defaultSessionConfiguration
:创建一个默认的NSURLSessionConfiguration
AFURLSessionManager
> - initWithSessionConfiguration
:初始化AFURLSessionManager 通过 NSURLSessionConfiguration
> - downloadTaskWithRequest
:创建 NSURLSessionDownloadTask 对象
NSURLSessionDownloadTask
> - resume
代码:
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//继承自AFURLSessionManager。类似于1和2的关系。也是方便HTTP以及https请求的使用,增加了一些接口,方便调用。
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfig];
NSURL *url = [NSURL URLWithString:@"http://www.361810.com/uploads/allimg/150409/2053363O4-0.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//progress 进度条 destination 最终地址 completionHandler 完成处理程序
NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSLog(@"%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]);
//创建下载地址
NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//这时候已经在主线程了
//先将filePath转换成data类型
NSData *data = [NSData dataWithContentsOfURL:filePath];
//转换成image
UIImage *image = [UIImage imageWithData:data];
_imageView.image = image;
}];
//继续操作
[downloadTask resume];
上传
get post 解析