HTTP通信過程
1.png
2.png
3.png
4.png
NSURLConnection發(fā)送網(wǎng)絡(luò)請求
block 方式
-
發(fā)送同步請求
發(fā)送同步請求 -
發(fā)送異步請求
異步請求
代理方式
代理方式發(fā)送請求
代理方法
POST請求
POST請求
中文URL處理
中文URL處理
JSON解析
JSON解析1
JSON解析練習(xí)
解析JSON
小文件下載NSData方式
NSURL *url = [NSURL URLWithString:@"https://XXX"];
NSData *data = [NSData dataWithContentsOfURL:url];
block方式下載小文件
// 0.請求路徑
NSURL *url = [NSURL URLWithString:@"http://xxx"];
// 1.創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.發(fā)送請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 請求完畢會來到這個block
// 3.解析服務(wù)器返回的數(shù)據(jù)(解析成字符串)
// 解析JSON
// NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.imageView.image = [UIImage imageWithData:data];
}];
代理下載大文件
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger contentLength;
/** 當(dāng)前下載的總長度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 輸出流對象 */
@property (nonatomic, strong) NSOutputStream *stream;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]] delegate:self];
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
// response.suggestedFilename : 服務(wù)器那邊的文件名
// 獲得文件的總長度
self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
// 文件路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@", file);
// 利用NSOutputStream往Path中寫入數(shù)據(jù)(append為YES的話,每次寫入都是追加到文件尾部)
self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
// 打開流(如果文件不存在,會自動創(chuàng)建)
[self.stream open];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.stream write:[data bytes] maxLength:data.length];
// 拼接總長度
self.currentLength += data.length;
// 進度
self.progressView.progress = 1.0 * self.currentLength / self.contentLength;
NSLog(@"didReceiveData-------");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.stream close];
// 清空長度
self.currentLength = 0;
NSLog(@"-------");
}
@end
NSURLConnection文件上傳,上傳文件要配置請求頭,要不區(qū)分不出是普通post還是文件上傳,參數(shù)體要有格式。反正很惡心的格式。
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1.創(chuàng)建請求
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 2. 設(shè)置請求頭(告訴服務(wù)器,這是一個文件上傳的請求)cxwl為分隔符
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", @"cxwl"] forHTTPHeaderField:@"Content-Type"];
request.timeoutInterval = 30;
UIImage *image = [UIImage imageNamed:@"1.png"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//3. 配置參數(shù)
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"token" forKey:@"xxxxx"];
[dic setObject:data forKey:@"file"];
//4.將文件參數(shù)和普通參數(shù)合成的字典傳入返回文件上傳所要的data
NSData *paramsData = [self getDataStringAndFileWithParams:dic];
request.HTTPBody = paramsData;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
}
#pragma mark - multipart格式轉(zhuǎn)換
// 把有文件的參數(shù)類型的字典轉(zhuǎn)換成data返回
- (NSData *)getDataStringAndFileWithParams:(NSDictionary *)params
{
// 1.創(chuàng)建一個可變data數(shù)據(jù)
NSMutableData *data = [[NSMutableData alloc] init];
// 2.遍歷參數(shù)進行拼接
for (NSString *key in params) {
// 3.獲取當(dāng)前參數(shù)對應(yīng)的值
id value = params[key];
// 4.判斷參數(shù)的類型
if ([value isKindOfClass:[NSData class]]) {
// 當(dāng)前是圖片參數(shù)
// 01 標(biāo)記參數(shù)的開始
[data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 02 添加參數(shù)的key
NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\";filename=\"img.png\" \r\n",key];
[data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
// 03 注視參數(shù)類型
[data appendData:[@"Content-Type;image/png \r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 04 添加參數(shù)的value
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:value];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
} else {
// 當(dāng)前是普通參數(shù)
// 01 標(biāo)記參數(shù)的開始
[data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 02 添加參數(shù)的key
NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\"\r\n",key];
[data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
// 03 添加參數(shù)的value
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
}
// 標(biāo)記結(jié)束
[data appendData:[@"--cxwl--" dataUsingEncoding:NSUTF8StringEncoding]];
return data;
}
@end
NSURLConnection與RunLoop
子線程發(fā)送請求,默認代理是不會調(diào)用的,因為線程已經(jīng)死了,所以要開啟runloop,讓線程活著.來調(diào)用代理,af2.0就是這個意思
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
/** runLoop */
@property (nonatomic, assign) CFRunLoopRef runLoop;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"]] delegate:self];
// 決定代理方法在哪個隊列中執(zhí)行
[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
// 啟動子線程的runLoop
// [[NSRunLoop currentRunLoop] run];
self.runLoop = CFRunLoopGetCurrent();
// 啟動runLoop
CFRunLoopRun();
});
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse----%@", [NSThread currentThread]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData----%@", [NSThread currentThread]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading----%@", [NSThread currentThread]);
// 停止RunLoop
CFRunLoopStop(self.runLoop);
}
@end
由于蘋果在 iOS9 之后已經(jīng)放棄了 NSURLConnection,所以在現(xiàn)在的實際開發(fā)中,除了大家常見的 AFN 框架,一般使用的是 iOS7 之后推出的 NSURLSession,作為一名 iOS 開發(fā)人員,得好好學(xué)學(xué)NSURLSession。
NSURLSession 的優(yōu)勢
NSURLSession 支持 http2.0 協(xié)議
在處理下載任務(wù)的時候可以直接把數(shù)據(jù)下載到磁盤
支持后臺下載|上傳
同一個 session 發(fā)送多個請求,只需要建立一次連接(復(fù)用了TCP)
提供了全局的 session 并且可以統(tǒng)一配置,使用更加方便
下載的時候是多線程異步處理,效率更高
NSURLSessionTask 的子類
NSURLSessionTask 是一個抽象類,如果要使用那么只能使用它的子類
NSURLSessionTask 有兩個子類
NSURLSessionDataTask,可以用來處理一般的網(wǎng)絡(luò)請求,如 GET | POST 請求等
NSURLSessionDataTask 有一個子類為 NSURLSessionUploadTask,用于處理上傳請求的時候有優(yōu)勢
NSURLSessionDownloadTask,主要用于處理下載請求,有很大的優(yōu)勢
NSURLSession 的子類如下圖:
1476705225200087.png
NSURLSession的get和post請求
- (void)post
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
request.HTTPMethod = @"POST"; // 請求方法
request.HTTPBody = [@"username=123&pwd=445" dataUsingEncoding:NSUTF8StringEncoding]; // 請求體
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
- (void)get2
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
- (void)get
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
NSURLSession代理方法
#import "ViewController.h"
//@protocol NSURLSessionDataDelegate <NSURLSessionTaskDelegate>
@interface ViewController () <NSURLSessionDataDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]]];
// 啟動任務(wù)
[task resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到服務(wù)器的響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 允許處理服務(wù)器的響應(yīng),才會繼續(xù)接收服務(wù)器返回的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器的數(shù)據(jù)(可能會被調(diào)用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"%s", __func__);
}
/**
* 3.請求成功或者失敗(如果失敗,error有值)
*/
#pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __func__);
}
@end
NSURLSession小文件下載
- (void)download
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 獲得下載任務(wù)
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 文件將來存放的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
// 啟動任務(wù)
[task resume];
}
NSURLSessionDataTask離線斷點,程序殺死進來
// 文件的存放路徑(caches)
#define XMGMp4File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.mp4"]
// 文件的已下載長度
#define XMGDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGMp4File error:nil][NSFileSize] integerValue]
#import "ViewController.h"
@interface ViewController () <NSURLSessionDataDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 寫文件的流對象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger totalLength;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
- (NSOutputStream *)stream
{
if (!_stream) {
_stream = [NSOutputStream outputStreamToFileAtPath:XMGMp4File append:YES];
}
return _stream;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", XMGMp4File);
}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// 設(shè)置請求頭
// Range : bytes=xxx-xxx
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 創(chuàng)建一個Data任務(wù)
self.task = [self.session dataTaskWithRequest:request];
// 啟動任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
/**
* 繼續(xù)下載
*/
- (IBAction)goOn:(id)sender {
[self.task resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 打開流
[self.stream open];
// 獲得服務(wù)器這次請求 返回數(shù)據(jù)的總長度
self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + XMGDownloadLength;
// 接收這個請求,允許接收服務(wù)器的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器返回的數(shù)據(jù)(這個方法可能會被調(diào)用N次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 寫入數(shù)據(jù)
[self.stream write:data.bytes maxLength:data.length];
// 下載進度
NSLog(@"%f", 1.0 * XMGDownloadLength / self.totalLength);
}
/**
* 3.請求完畢(成功\失敗)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 關(guān)閉流
[self.stream close];
self.stream = nil;
}
@end
NSURLSession大文件下載,下面的demo不支持退出程序進來后斷點下載,因為沒有做緩存,NSURLSessionDownloadTask下載的文件,是臨時的所以做緩存處理起來復(fù)雜,用NSURLSessionDataTask做比較容易。看我的另一篇文章用NSURLSessionDataTask文件下載。支持斷點續(xù)傳。但是他有個缺點就是不能夠后臺下載,這是個缺陷,想要做后臺下載還得用NSURLSessionDownloadTask http://www.lxweimin.com/p/9b66e757590e
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
/** 保存上次的下載信息 */
@property (nonatomic, strong) NSData *resumeData;
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
if (self.resumeData) {
// 獲得上次的下載任務(wù)
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
} else {
// 獲得下載任務(wù)
self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
}
// 啟動任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
// 一旦這個task被取消了,就無法再恢復(fù)
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
}];
}
/**
* 繼續(xù)下載
*/
- (IBAction)goOn:(id)sender {
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
// 保存恢復(fù)數(shù)據(jù)
self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"didResumeAtOffset");
}
/**
* 每當(dāng)寫入數(shù)據(jù)到臨時文件時,就會調(diào)用一次這個方法
* totalBytesExpectedToWrite:總大小
* totalBytesWritten: 已經(jīng)寫入的大小
* bytesWritten: 這次寫入多少
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
/**
*
* 下載完畢就會調(diào)用一次這個方法
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// 文件將來存放的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
@end
NSURLSession文件上傳
#import "ViewController.h"
@interface ViewController ()
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
cfg.timeoutIntervalForRequest = 10;
// 是否允許使用蜂窩網(wǎng)絡(luò)(手機自帶網(wǎng)絡(luò))
cfg.allowsCellularAccess = YES;
_session = [NSURLSession sessionWithConfiguration:cfg];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 1.創(chuàng)建請求
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 2. 設(shè)置請求頭(告訴服務(wù)器,這是一個文件上傳的請求)cxwl為分隔符
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", @"cxwl"] forHTTPHeaderField:@"Content-Type"];
request.timeoutInterval = 30;
UIImage *image = [UIImage imageNamed:@"1.png"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//3. 配置參數(shù)
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"token" forKey:@"xxxxx"];
[dic setObject:data forKey:@"file"];
//4.將文件參數(shù)和普通參數(shù)合成的字典傳入返回文件上傳所要的data
NSData *paramsData = [self getDataStringAndFileWithParams:dic];
[[self.session uploadTaskWithRequest:request fromData:paramsData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
}
#pragma mark - multipart格式轉(zhuǎn)換
// 把有文件的參數(shù)類型的字典轉(zhuǎn)換成data返回
- (NSData *)getDataStringAndFileWithParams:(NSDictionary *)params
{
// 1.創(chuàng)建一個可變data數(shù)據(jù)
NSMutableData *data = [[NSMutableData alloc] init];
// 2.遍歷參數(shù)進行拼接
for (NSString *key in params) {
// 3.獲取當(dāng)前參數(shù)對應(yīng)的值
id value = params[key];
// 4.判斷參數(shù)的類型
if ([value isKindOfClass:[NSData class]]) {
// 當(dāng)前是圖片參數(shù)
// 01 標(biāo)記參數(shù)的開始
[data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 02 添加參數(shù)的key
NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\";filename=\"img.png\" \r\n",key];
[data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
// 03 注視參數(shù)類型
[data appendData:[@"Content-Type;image/png \r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 04 添加參數(shù)的value
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:value];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
} else {
// 當(dāng)前是普通參數(shù)
// 01 標(biāo)記參數(shù)的開始
[data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 02 添加參數(shù)的key
NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\"\r\n",key];
[data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
// 03 添加參數(shù)的value
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
}
// 標(biāo)記結(jié)束
[data appendData:[@"--cxwl--" dataUsingEncoding:NSUTF8StringEncoding]];
return data;
}
@end