iOS网络NSURLConnection和NSURLSession

HTTP通信过程

iOS网络NSURLConnection和NSURLSession_第1张图片
1.png
iOS网络NSURLConnection和NSURLSession_第2张图片
2.png
iOS网络NSURLConnection和NSURLSession_第3张图片
3.png
iOS网络NSURLConnection和NSURLSession_第4张图片
4.png

NSURLConnection发送网络请求

block 方式

  • 发送同步请求


    iOS网络NSURLConnection和NSURLSession_第5张图片
    发送同步请求
  • 发送异步请求


    iOS网络NSURLConnection和NSURLSession_第6张图片
    异步请求

代理方式

iOS网络NSURLConnection和NSURLSession_第7张图片
代理方式发送请求
iOS网络NSURLConnection和NSURLSession_第8张图片
代理方法

POST请求

iOS网络NSURLConnection和NSURLSession_第9张图片
POST请求

中文URL处理

iOS网络NSURLConnection和NSURLSession_第10张图片
中文URL处理

JSON解析

iOS网络NSURLConnection和NSURLSession_第11张图片
JSON解析1

iOS网络NSURLConnection和NSURLSession_第12张图片
JSON解析练习
iOS网络NSURLConnection和NSURLSession_第13张图片
解析JSON

小文件下载NSData方式

NSURL *url = [NSURL URLWithString:@"https://XXX"];
NSData *data = [NSData dataWithContentsOfURL:url];

block方式下载小文件

 // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://xxx"];
    
    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 请求完毕会来到这个block
        // 3.解析服务器返回的数据(解析成字符串)
      // 解析JSON
      //  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

      self.imageView.image = [UIImage imageWithData:data];
    }];

代理下载大文件

#import "ViewController.h"

@interface ViewController () 

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger contentLength;
/** 当前下载的总长度 */
@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 - 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    // response.suggestedFilename : 服务器那边的文件名
    // 获得文件的总长度
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
    NSLog(@"%@", file);
    
    // 利用NSOutputStream往Path中写入数据(append为YES的话,每次写入都是追加到文件尾部)
    self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
    // 打开流(如果文件不存在,会自动创建)
    [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文件上传,上传文件要配置请求头,要不区分不出是普通post还是文件上传,参数体要有格式。反正很恶心的格式。

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.创建请求
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    // 2. 设置请求头(告诉服务器,这是一个文件上传的请求)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. 配置参数
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"token" forKey:@"xxxxx"];
    [dic setObject:data forKey:@"file"];
    
    //4.将文件参数和普通参数合成的字典传入返回文件上传所要的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格式转换
// 把有文件的参数类型的字典转换成data返回
- (NSData *)getDataStringAndFileWithParams:(NSDictionary *)params
{
    // 1.创建一个可变data数据
    NSMutableData *data = [[NSMutableData alloc] init];
    
    // 2.遍历参数进行拼接
    for (NSString *key in params) {
        // 3.获取当前参数对应的值
        id value = params[key];
        // 4.判断参数的类型
        if ([value isKindOfClass:[NSData class]]) {
            // 当前是图片参数
            // 01 标记参数的开始
            [data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            // 02 添加参数的key
            NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\";filename=\"img.png\" \r\n",key];
            [data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
            // 03 注视参数类型
            [data appendData:[@"Content-Type;image/png \r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            // 04 添加参数的value
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:value];
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
        } else {
            // 当前是普通参数
            // 01 标记参数的开始
            [data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            // 02 添加参数的key
            NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\"\r\n",key];
            [data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
            // 03 添加参数的value
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
    }
    // 标记结束
    [data appendData:[@"--cxwl--" dataUsingEncoding:NSUTF8StringEncoding]];
    
    return data;
}


@end

NSURLConnection与RunLoop

子线程发送请求,默认代理是不会调用的,因为线程已经死了,所以要开启runloop,让线程活着.来调用代理,af2.0就是这个意思

#import "ViewController.h"

@interface ViewController () 
/** 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];
        // 决定代理方法在哪个队列中执行
        [conn setDelegateQueue:[[NSOperationQueue alloc] init]];
        
        // 启动子线程的runLoop
//        [[NSRunLoop currentRunLoop] run];
        
        self.runLoop = CFRunLoopGetCurrent();
        
        // 启动runLoop
        CFRunLoopRun();
    });
}

#pragma mark - 
- (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 之后已经放弃了 NSURLConnection,所以在现在的实际开发中,除了大家常见的 AFN 框架,一般使用的是 iOS7 之后推出的 NSURLSession,作为一名 iOS 开发人员,得好好学学NSURLSession。

NSURLSession 的优势

NSURLSession 支持 http2.0 协议
在处理下载任务的时候可以直接把数据下载到磁盘
支持后台下载|上传
同一个 session 发送多个请求,只需要建立一次连接(复用了TCP)
提供了全局的 session 并且可以统一配置,使用更加方便
下载的时候是多线程异步处理,效率更高

NSURLSessionTask 的子类

NSURLSessionTask 是一个抽象类,如果要使用那么只能使用它的子类
NSURLSessionTask 有两个子类
NSURLSessionDataTask,可以用来处理一般的网络请求,如 GET | POST 请求等
NSURLSessionDataTask 有一个子类为 NSURLSessionUploadTask,用于处理上传请求的时候有优势
NSURLSessionDownloadTask,主要用于处理下载请求,有很大的优势

NSURLSession 的子类如下图:

iOS网络NSURLConnection和NSURLSession_第14张图片
1476705225200087.png

NSURLSession的get和post请求

- (void)post
{
    // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
    request.HTTPMethod = @"POST"; // 请求方法
    request.HTTPBody = [@"username=123&pwd=445" dataUsingEncoding:NSUTF8StringEncoding]; // 请求体
    
    // 创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
    }];
    
    // 启动任务
    [task resume];
}

- (void)get2
{
    // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 创建任务
    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]);
    }];
    
    // 启动任务
    [task resume];
}

- (void)get
{
    // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 创建任务
    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]);
    }];
    
    // 启动任务
    [task resume];
}

NSURLSession代理方法

#import "ViewController.h"

//@protocol NSURLSessionDataDelegate 
@interface ViewController () 

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    // 创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]]];
    // 启动任务
    [task resume];
}

#pragma mark - 
/**
 * 1.接收到服务器的响应
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 允许处理服务器的响应,才会继续接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}

/**
 * 2.接收到服务器的数据(可能会被调用多次)
 */
- (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];
    
    // 获得下载任务
    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];
        
        // 剪切location的临时文件到真实路径
        NSFileManager *mgr = [NSFileManager defaultManager];
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }];
    
    // 启动任务
    [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 () 
/** 下载任务 */
@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 {
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
    
    // 设置请求头
    // Range : bytes=xxx-xxx
    NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength];
    [request setValue:range forHTTPHeaderField:@"Range"];
    
    // 创建一个Data任务
    self.task = [self.session dataTaskWithRequest:request];
    
    // 启动任务
    [self.task resume];
}

/**
 * 暂停下载
 */
- (IBAction)pause:(id)sender {
    [self.task suspend];
}

/**
 * 继续下载
 */
- (IBAction)goOn:(id)sender {
    [self.task resume];
}

#pragma mark - 
/**
 * 1.接收到响应
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 打开流
    [self.stream open];
    
    // 获得服务器这次请求 返回数据的总长度
    self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + XMGDownloadLength;
    
    // 接收这个请求,允许接收服务器的数据
    completionHandler(NSURLSessionResponseAllow);
}

/**
 * 2.接收到服务器返回的数据(这个方法可能会被调用N次)
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    // 写入数据
    [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
{
    // 关闭流
    [self.stream close];
    self.stream = nil;
}

@end

NSURLSession大文件下载,下面的demo不支持退出程序进来后断点下载,因为没有做缓存,NSURLSessionDownloadTask下载的文件,是临时的所以做缓存处理起来复杂,用NSURLSessionDataTask做比较容易。看我的另一篇文章用NSURLSessionDataTask文件下载。支持断点续传。但是他有个缺点就是不能够后台下载,这是个缺陷,想要做后台下载还得用NSURLSessionDownloadTask http://www.jianshu.com/p/9b66e757590e

#import "ViewController.h"

@interface ViewController () 
/** 下载任务 */
@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) {
        // 获得上次的下载任务
        self.task = [self.session downloadTaskWithResumeData:self.resumeData];
        
    } else {
        // 获得下载任务
        self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
    }
    
    // 启动任务
    [self.task resume];
}

/**
 * 暂停下载
 */
- (IBAction)pause:(id)sender {
    // 一旦这个task被取消了,就无法再恢复
    [self.task cancelByProducingResumeData:^(NSData *resumeData) {
        self.resumeData = resumeData;

    }];
}


/**
 * 继续下载
 */
- (IBAction)goOn:(id)sender {
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];

    [self.task resume];
}

#pragma mark - 
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"didCompleteWithError");
    
    // 保存恢复数据
    self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    NSLog(@"didResumeAtOffset");
}

/**
 * 每当写入数据到临时文件时,就会调用一次这个方法
 * totalBytesExpectedToWrite:总大小
 * totalBytesWritten: 已经写入的大小
 * 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);
}


/**
 * 
 * 下载完毕就会调用一次这个方法
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    // 文件将来存放的真实路径
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    // 剪切location的临时文件到真实路径
    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;
        // 是否允许使用蜂窝网络(手机自带网络)
        cfg.allowsCellularAccess = YES;
        _session = [NSURLSession sessionWithConfiguration:cfg];
    }
    return _session;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.创建请求
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    // 2. 设置请求头(告诉服务器,这是一个文件上传的请求)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. 配置参数
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"token" forKey:@"xxxxx"];
    [dic setObject:data forKey:@"file"];
    
    //4.将文件参数和普通参数合成的字典传入返回文件上传所要的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格式转换
// 把有文件的参数类型的字典转换成data返回
- (NSData *)getDataStringAndFileWithParams:(NSDictionary *)params
{
    // 1.创建一个可变data数据
    NSMutableData *data = [[NSMutableData alloc] init];
    
    // 2.遍历参数进行拼接
    for (NSString *key in params) {
        // 3.获取当前参数对应的值
        id value = params[key];
        // 4.判断参数的类型
        if ([value isKindOfClass:[NSData class]]) {
            // 当前是图片参数
            // 01 标记参数的开始
            [data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            // 02 添加参数的key
            NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\";filename=\"img.png\" \r\n",key];
            [data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
            // 03 注视参数类型
            [data appendData:[@"Content-Type;image/png \r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            // 04 添加参数的value
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:value];
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
        } else {
            // 当前是普通参数
            // 01 标记参数的开始
            [data appendData:[@"--cxwl\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            // 02 添加参数的key
            NSString *keyString = [NSString stringWithFormat:@"Content-Disposition:form-data;name=\"%@\"\r\n",key];
            [data appendData:[keyString dataUsingEncoding:NSUTF8StringEncoding]];
            // 03 添加参数的value
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
    }
    // 标记结束
    [data appendData:[@"--cxwl--" dataUsingEncoding:NSUTF8StringEncoding]];
    
    return data;
}

@end

NSURLSession其他文章

http://www.jianshu.com/p/fafc67475c73

你可能感兴趣的:(iOS网络NSURLConnection和NSURLSession)