小小感言
本来是想写博客来着,朋友说简书的排版更好些,于是就来试试。
总想着把自己开发中遇到的技术点、问题还有大大小小的坑都总结出来,但就是一直没有时间写,或者可能是自己没有养成写的好习惯并坚持下去吧,平常也就是在备忘录、文档里那么随便一记,以后得好好改进了。
这篇文章我就总结一下自己网络请求和上传数据的时候用到的afn3.0
AFNetworking 介绍
AFNetworking 1.0是建立在NSURLConnection的基础API上的 ,AFNetworking 2.0开始使用NSURLConnection的基础API ,以及较新基于NSURLSession的API的选项。 AFNetworking 3.0现已完全基于NSURLSession的API,这降低了维护的负担,同时支持苹果增强关于NSURLSession提供的任何额外功能。由于Xcode 7中,NSURLConnection的API已经正式被苹果弃用。虽然该API将继续运行,但将没有新功能将被添加,并且苹果已经通知所有基于网络的功能,以充分使NSURLSession向前发展。
AFNetworking 3.0正式支持的iOS 7, Mac OS X的10.9, watchOS 2 , tvOS 9 和Xcode 7。
在AFNetworking3.0中下面这些类已被废弃:
- AFURLConnectionOperation
- AFHTTPRequestOperation
- AFHTTPRequestOperationManager
另外这些类包含基于NSURLConnection的API的内部实现,他们已经被使用NSURLSession重构:
- UIImageView+AFNetworking
- UIWebView+AFNetworking
- UIButton+AFNetworking
Post请求
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval= 20;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", nil];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy = securityPolicy;
[manager POST:urlStr parameters:dic success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"请求成功");
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"%@ error" , error);
}];
Get请求
因为项目里用到的都是post请求,get请求我就简单的附上
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功");
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
上传图片
-(void)PostUploadImage:(NSMutableDictionary*)dic Url:(NSString *)url
{
UIImage *image = [dic valueForKey:@"pic"];//图片以键值对的形式存为了一个字典
NSData *data =UIImageJPEGRepresentation(image , 0.5);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"%@error" , error);
}else{
NSString *str = [[ NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dic = [ NSDictionary dictionary];
dic = [self dictionaryWithJsonString:str];
self.Block(dic);//返回数据
}
}];
[dataTask resume];
}
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
上传多张图片
-(void)POSTuploadImages:(NSArray*)imageArray url:(NSString*)url
{
NSError* error = NULL;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (int i = 0; i<imageArray.count; i++) {
NSData *uploadImage = imageArray[i];//数组里存储的已经将UIImage转化为了NSData
// 上传的参数名
NSString * Name = [NSString stringWithFormat:@"%d",i+1];
// 上传filename
NSString * fileName = [NSString stringWithFormat:@"%@.png", Name];
[formData appendPartWithFileData:uploadImage name:Name fileName:fileName mimeType:@"image/png"];
}
} error:&error];
// 可在此处配置验证信息
// 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask =[manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSString *str = [[ NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
NSDictionary *dic = [ NSDictionary dictionary];
dic = [self dictionaryWithJsonString:str];
NSLog(@"%@===========",dic);//最终的数据
self.Block(dic);//使用block返回数据
}];
}
上传录音文件
-(void)POSTuploadSound:(NSMutableDictionary*)dic url:(NSString*)url
{
NSData *data= [dic valueForKey:@"Sound"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"%@error" , error);
}else{
NSString *str = [[ NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dic = [ NSDictionary dictionary];
dic = [self dictionaryWithJsonString:str];
self.Block(dic);
}
}];
[dataTask resume];
}
下载
-(void)downLoadUrl:(NSString *)url{
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.请求的URL地址
NSURL *url = [NSURL URLWithString:url];
//3.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//打印下下载进度
NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
}
destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//下载地址
NSLog(@"默认下载地址:%@",targetPath);
//设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象 NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
return [NSURL URLWithString:filePath];
}
completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//下载完成调用的方法
NSLog(@"下载完成");
NSLog(@"%@---------------%@",response,filePath); }];
//开始启动任务
[task resume];
}
网络监听
-(BOOL)isNetWorkReachable{
AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
[afNetworkReachabilityManager startMonitoring]; //开启网络监视器;
[afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
// 设置图片
hud.labelText = @"无网络 ,请检查网络连接";
// 再设置模式
hud.mode = MBProgressHUDModeCustomView;
hud.center = self.window.center;
// 隐藏时候从父控件中移除
hud.removeFromSuperViewOnHide = YES;
// 2秒之后再消失
[hud hide:YES afterDelay:2];
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi:{
NSLog(@"WiFi" );
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN:{
NSLog(@"数据网络" );
break;
}
case AFNetworkReachabilityStatusUnknown:{
NSLog(@"未知网络" );
break;
}
default:
break;
}
}];
return [AFNetworkReachabilityManager sharedManager].isReachable;
}