AFNetworking大家都不陌生,本文对其进行了最简单的封装,功能实现:GET、POST、单文件上传、多文件上传、文件下载。
先用java Spring Boot模拟实现后台接口
对后台不懂的同学可以略过,模拟使用的Spring Boot实现的RestFul接口。直接上码
package com.moxi.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.moxi.model.ResObject;
import com.moxi.model.User;
import com.moxi.util.Constant;
@RestController
public class AppController {
/*
* GET请求
*/
@GetMapping("/app/login")
public ResObject<Object> login(User user) {
System.out.println("UserName :" + user.getUserName());
System.out.println("Password" + user.getPassword());
ResObject<Object> object = new ResObject<Object>(Constant.Code01, Constant.Msg01, user, null);
return object;
}
/*
* POST请求
*/
@PostMapping("/app/register")
public ResObject<Object> register(User user) {
System.out.println("UserName :" + user.getUserName());
System.out.println("Password" + user.getPassword());
ResObject<Object> object = new ResObject<Object>(Constant.Code01, Constant.Msg01, user, null);
return object;
}
/*
* 单文件上传
*/
@PostMapping("/app/upload")
public ResObject<Object> upload(User user,@RequestParam MultipartFile imageFile,HttpSession httpSession) {
System.out.println("UserName :" + user.getUserName());
System.out.println("Password" + user.getPassword());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new java.util.Date();
String strDate = sdf.format(date);
String fileName = strDate + imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().indexOf("."),imageFile.getOriginalFilename().length());
String realPath = httpSession.getServletContext().getRealPath("/userfiles");
System.out.println("realPath : "+realPath);
try {
FileUtils.copyInputStreamToFile(imageFile.getInputStream(),new File(realPath, fileName));
} catch (IOException e) {
e.printStackTrace();
}
ResObject<Object> object = new ResObject<Object>(Constant.Code01, Constant.Msg01, user, null);
return object;
}
/*
* 多文件上传
*/
@PostMapping("/app/uploads")
public ResObject<Object> uploads(User user, @RequestParam MultipartFile[] imageFile,HttpSession httpSession) {
System.out.println("UserName :" + user.getUserName());
System.out.println("Password" + user.getPassword());
for (MultipartFile file : imageFile) {
if (file.isEmpty()) {
System.out.println("文件未上传");
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Random random = new Random();
Date date = new java.util.Date();
String strDate = sdf.format(date);
String fileName = strDate + random.nextInt(1000) + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."),file.getOriginalFilename().length());
String realPath = httpSession.getServletContext().getRealPath("/userfiles");
System.out.println("realPath : "+realPath);
System.out.println("fileName : "+fileName);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(realPath, fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
ResObject<Object> object = new ResObject<Object>(Constant.Code01, Constant.Msg01, user, null);
return object;
}
}
GET请求的结果如图,返回的是JSON格式数据
AFNetworking简单封装
定义SSNetworkingManager
继承自AFHTTPSessionManager
,并实现单利方法,此处希望有看过AF源码的同学给出建议,是用单利比较合适还是每个请求都初始化一个AFHTTPSessionManager
。
SSNetworkingManager.h
//
// SSNetworkingManager.h
// SZSSV1
//
// Created by DaLei on 2017/6/10.
// Copyright © 2017年 DaLei. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
#import "SSConfig.h"
@class SSImageModel;
typedef void (^ _Nullable Success)(id _Nullable responseObject);// 成功Block
typedef void (^ _Nullable Failure)(NSError * _Nullable error);// 失败Blcok
typedef void (^ _Nullable Progress)(NSProgress * _Nullable progress);// 上传或者下载进度Block
typedef NSURL * _Nullable (^ _Nullable Destination)(NSURL * _Nullable targetPath, NSURLResponse * _Nullable response);// 返回URL的Block
typedef void (^ _Nullable DownLoadSuccess)(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath);// 下载成功的Blcok
/**
对AF进行简单封装
*/
@interface SSNetworkingManager : AFHTTPSessionManager
/**
单利方法
@return 实例
*/
+(instancetype _Nonnull )shareManager;
/**
* 封装的GET请求
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param success 请求成功回调
* @param failure 请求失败回调
*/
- (void)GET:(NSString *_Nonnull)URLString parameters:(NSDictionary *_Nullable)parameters success:(Success)success failure:(Failure)failure;
/**
* 封装的POST请求
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param success 请求成功回调
* @param failure 请求失败回调
*/
- (void)POST:(NSString *_Nonnull)URLString parameters:(NSDictionary *_Nullable)parameters success:(Success)success failure:(Failure)failure;
/**
* 封装POST图片上传(多张图片) // 可扩展成多个别的数据上传如:mp3等
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param picArray 存放图片模型(HDPicModle)的数组
* @param progress 进度的回调
* @param success 发送成功的回调
* @param failure 发送失败的回调
*/
- (void)POST:(NSString *_Nonnull)URLString parameters:(NSDictionary *_Nullable)parameters andPicArray:(NSArray *_Nullable)picArray progress:(Progress)progress success:(Success)success failure:(Failure)failure;
/**
* 封装POST图片上传(单张图片) // 可扩展成单个别的数据上传如:mp3等
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param imageModle 上传的图片模型
* @param progress 进度的回调
* @param success 发送成功的回调
* @param failure 发送失败的回调
*/
- (void)POST:(NSString *_Nonnull)URLString parameters:(NSDictionary *_Nullable)parameters andPic:(SSImageModel *_Nullable)imageModle progress:(Progress)progress success:(Success)success failure:(Failure)failure;
/**
* 封装POST上传url资源
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param imageModle 上传的图片模型(资源的url地址)
* @param progress 进度的回调
* @param success 发送成功的回调
* @param failure 发送失败的回调
*/
- (void)POST:(NSString *_Nonnull)URLString parameters:(NSDictionary *_Nullable)parameters andPicUrl:(SSImageModel *_Nullable)imageModle progress:(Progress)progress success:(Success)success failure:(Failure)failure;
/**
* 下载
*
* @param URLString 请求的链接
* @param progress 进度的回调
* @param destination 返回URL的回调
* @param downLoadSuccess 发送成功的回调
* @param failure 发送失败的回调
*/
- (NSURLSessionDownloadTask *_Nonnull)downLoadWithURL:(NSString *_Nonnull)URLString progress:(Progress)progress destination:(Destination)destination downLoadSuccess:(DownLoadSuccess)downLoadSuccess failure:(Failure)failure;
@end
SSNetworkingManager.m
//
// SSNetworkingManager.m
// SZSSV1
//
// Created by DaLei on 2017/6/10.
// Copyright © 2017年 DaLei. All rights reserved.
//
#import "SSNetworkingManager.h"
#import "SSImageModel.h"
@implementation SSNetworkingManager
+(instancetype)shareManager{
static SSNetworkingManager *manager = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
manager = [[self alloc] initWithBaseURL:[NSURL URLWithString:URL_BASE]];
});
return manager;
}
/**
重写父类方法
@param url baseUrl
@return 通过重写夫类的initWithBaseURL方法,返回网络请求类的实例
*/
-(instancetype)initWithBaseURL:(NSURL *)url{
if (self = [super initWithBaseURL:url]) {
/**设置请求超时时间*/
self.requestSerializer.timeoutInterval = 30;
/**设置相应的缓存策略*/
self.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
/**将token封装入请求头*/
[self.requestSerializer setValue:@"TOKEN" forHTTPHeaderField:@"TOKENID"];
/**设置可接受的类型*/
[self.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html", nil]];
/**设置请求和返回数据格式*/
self.requestSerializer = [AFHTTPRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
}
return self;
}
/**
* 封装的get请求
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param success 请求成功回调
* @param failure 请求失败回调
*/
- (void)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(Success)success failure:(Failure)failure {
SSLog(@"\n请求链接地址---> %@",URLString);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
SSLog(@"请求成功,返回数据 : %@",responseObject);
success(responseObject);
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
SSLog(@"请求失败:%@",error);
failure(error);
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}];
}
/**
* 封装的POST请求
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param success 请求成功回调
* @param failure 请求失败回调
*/
- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(Success)success failure:(Failure)failure {
SSLog(@"\n请求链接地址---> %@",URLString);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; // 开启状态栏动画
[self POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
SSLog(@"请求成功,返回数据 : %@",responseObject);
success(responseObject);
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; // 关闭状态栏动画
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
SSLog(@"请求失败:%@",error);
failure(error);
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; // 关闭状态栏动画
}];
}
/**
* 封装POST图片上传(多张图片) // 可扩展成多个别的数据上传如:mp3等
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param picArray 存放图片模型(HDPicModle)的数组
* @param progress 进度的回调
* @param success 发送成功的回调
* @param failure 发送失败的回调
*/
- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters andPicArray:(NSArray *)picArray progress:(Progress)progress success:(Success)success failure:(Failure)failure {
SSLog(@"\n请求链接地址---> %@",URLString);
[self POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSInteger count = picArray.count;
NSString *fileName = @"";
NSData *data = [NSData data];
for (int i = 0; i < count; i++) {
@autoreleasepool {
SSImageModel *picModle = picArray[i];
fileName = [NSString stringWithFormat:@"pic%02d.jpg", i];
/**
* 压缩图片然后再上传(1.0代表无损 0~~1.0区间)
*/
data = UIImageJPEGRepresentation(picModle.image, 1.0);
[formData appendPartWithFileData:data name:picModle.imageName fileName:fileName mimeType:@"image/jpeg"];
data = nil;
picModle.image = nil;
}
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
if (progress) {
progress(uploadProgress); // HDLog(@"%lf", 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
}
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
SSLog(@"请求成功,返回数据 : %@",responseObject);
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
SSLog(@"请求失败:%@",error);
failure(error);
}
}];
}
/**
* 封装POST图片上传(单张图片) // 可扩展成单个别的数据上传如:mp3等
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param picModle 上传的图片模型
* @param progress 进度的回调
* @param success 发送成功的回调
* @param failure 发送失败的回调
*/
- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters andPic:(SSImageModel *)picModle progress:(Progress)progress success:(Success)success failure:(Failure)failure {
SSLog(@"\n请求链接地址---> %@",URLString);
[self POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
/**
* 压缩图片然后再上传(1.0代表无损 0~~1.0区间)
*/
NSData *data = UIImageJPEGRepresentation(picModle.image, 1.0);
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", picModle.imageName];
[formData appendPartWithFileData:data name:picModle.imageName fileName:fileName mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
if (progress) {
progress(uploadProgress);
SSLog(@"%lf", 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
}
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
SSLog(@"请求成功,返回数据 : %@",responseObject);
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
SSLog(@"请求失败:%@",error);
failure(error);
}
}];
}
/**
* 封装POST上传url资源
*
* @param URLString 请求的链接
* @param parameters 请求的参数
* @param picModle 上传的图片模型(资源的url地址)
* @param progress 进度的回调
* @param success 发送成功的回调
* @param failure 发送失败的回调
*/
- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters andPicUrl:(SSImageModel *)picModle progress:(Progress)progress success:(Success)success failure:(Failure)failure {
SSLog(@"\n请求链接地址---> %@",URLString);
[self POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", picModle.imageName];
// 根据本地路径获取url(相册等资源上传)
NSURL *url = [NSURL fileURLWithPath:picModle.url]; // [NSURL URLWithString:picModle.url] 可以换成网络的图片在上传
[formData appendPartWithFileURL:url name:picModle.imageName fileName:fileName mimeType:@"application/octet-stream" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {
if (progress) {
progress(uploadProgress);
SSLog(@"%lf", 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
}
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
SSLog(@"请求成功,返回数据 : %@",responseObject);
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
SSLog(@"请求失败:%@",error);
failure(error);
}
}];
}
/**
* 下载
*
* @param URLString 请求的链接
* @param progress 进度的回调
* @param destination 返回URL的回调
* @param downLoadSuccess 发送成功的回调
* @param failure 发送失败的回调
*/
- (NSURLSessionDownloadTask *)downLoadWithURL:(NSString *)URLString progress:(Progress)progress destination:(Destination)destination downLoadSuccess:(DownLoadSuccess)downLoadSuccess failure:(Failure)failure {
SSLog(@"\n请求链接地址---> %@",URLString);
NSURL *url = [NSURL URLWithString:URLString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 下载任务
NSURLSessionDownloadTask *task = [self downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
if (progress) {
progress(downloadProgress);
SSLog(@"%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
}
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
if (destination) {
return destination(targetPath, response);
} else {
return nil;
}
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if (error) {
SSLog(@"请求失败:%@",error);
failure(error);
} else {
SSLog(@"请求成功,返回数据 : %@",response);
downLoadSuccess(response, filePath);
}
}];
// 开始启动任务
[task resume];
return task;
}
@end
测试类TestNetworkViewController
TestNetworkViewController.m
//
// TestNetworkViewController.m
// SZSSV1
//
// Created by DaLei on 2017/6/13.
// Copyright © 2017年 DaLei. All rights reserved.
//
#import "TestNetworkViewController.h"
#import "SSNetworkingManager.h"
#import "SSImageModel.h"
@interface TestNetworkViewController ()
@end
@implementation TestNetworkViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)GET:(id)sender{
NSDictionary *dict = @{@"userName":@"xxx",@"password":@"yyy"};
[[SSNetworkingManager shareManager] GET:@"app/login" parameters:dict success:^(id _Nullable responseObject) {
} failure:^(NSError * _Nullable error) {
}];
}
-(IBAction)POST:(id)sender{
NSDictionary *dict = @{@"userName":@"xxx",@"password":@"yyy"};
[[SSNetworkingManager shareManager] POST:@"app/register" parameters:dict success:^(id _Nullable responseObject) {
} failure:^(NSError * _Nullable error) {
}];
}
-(IBAction)UPLOAD:(id)sender{
NSDictionary *dict = @{@"userName":@"xxx",@"password":@"yyy"};
SSImageModel *imageModel = [SSImageModel new];
imageModel.imageName = @"imageFile";
imageModel.image = [UIImage imageNamed:@"load1.png"];
[[SSNetworkingManager shareManager] POST:@"app/upload" parameters:dict andPic:imageModel progress:^(NSProgress * _Nullable progress) {
} success:^(id _Nullable responseObject) {
} failure:^(NSError * _Nullable error) {
}];
}
-(IBAction)UPLOADS:(id)sender{
NSDictionary *dict = @{@"userName":@"xxx",@"password":@"yyy"};
SSImageModel *imageModel1 = [SSImageModel new];
imageModel1.imageName = @"imageFile";
imageModel1.image = [UIImage imageNamed:@"load1.png"];
SSImageModel *imageModel2 = [SSImageModel new];
imageModel2.imageName = @"imageFile";
imageModel2.image = [UIImage imageNamed:@"load2.png"];
SSImageModel *imageModel3 = [SSImageModel new];
imageModel3.imageName = @"imageFile";
imageModel3.image = [UIImage imageNamed:@"load3.png"];
NSArray *array = @[imageModel1,imageModel2,imageModel3];
[[SSNetworkingManager shareManager] POST:@"app/uploads" parameters:dict andPicArray:array progress:^(NSProgress * _Nullable progress) {
} success:^(id _Nullable responseObject) {
} failure:^(NSError * _Nullable error) {
}];
}
-(IBAction)UPLOADURL:(id)sender{
NSDictionary *dict = @{@"userName":@"xxx",@"password":@"yyy"};
SSImageModel *imageModel1 = [SSImageModel new];
NSString *newPath=[[NSBundle mainBundle] pathForResource:@"Icon@3x" ofType:@"png"];
imageModel1.url = newPath;
imageModel1.imageName = @"imageFile";
[[SSNetworkingManager shareManager] POST:@"app/upload" parameters:dict andPicUrl:imageModel1 progress:^(NSProgress * _Nullable progress) {
} success:^(id _Nullable responseObject) {
} failure:^(NSError * _Nullable error) {
}];
}
-(IBAction)DOWNLOAD:(id)sender{
[[SSNetworkingManager shareManager] downLoadWithURL:@"http://localhost:8080/moxi-0.0.1-SNAPSHOT/userfiles/20170612110517.png" progress:^(NSProgress * _Nullable progress) {
} destination:^NSURL * _Nullable(NSURL * _Nullable targetPath, NSURLResponse * _Nullable response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} downLoadSuccess:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath) {
NSLog(@"response:%@,filePath:%@",response,filePath);
//判断目录里面是否存在这个图片
NSFileManager*fileManager = [NSFileManager defaultManager];
BOOL isFile = [fileManager fileExistsAtPath:[filePath path]];
if (isFile) {
//更新界面需要使用主线程
dispatch_async(dispatch_get_main_queue(), ^{
//设置图片视图的的图片
self.imageVC.image = [UIImage imageWithContentsOfFile:[filePath path]];
});
}
} failure:^(NSError * _Nullable error) {
}];
}
@end
执行结果