iOS网络NSURLConnection和NSURLSession

HTTP通信过程

1.png
2.png
3.png
4.png

NSURLConnection发送网络请求

block 方式

  • 发送同步请求


    发送同步请求
  • 发送异步请求


    异步请求

代理方式

代理方式发送请求
代理方法

POST请求

POST请求

中文URL处理

中文URL处理

JSON解析

JSON解析1

JSON解析练习
解析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 () <NSURLConnectionDataDelegate>

@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 - <NSURLConnectionDataDelegate>
- (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 () <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];
        // 决定代理方法在哪个队列中执行
        [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 之后已经放弃了 NSURLConnection,所以在现在的实际开发中,除了大家常见的 AFN 框架,一般使用的是 iOS7 之后推出的 NSURLSession,作为一名 iOS 开发人员,得好好学学NSURLSession。

NSURLSession 的优势

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

NSURLSessionTask 的子类

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

NSURLSession 的子类如下图:

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 <NSURLSessionTaskDelegate>
@interface ViewController () <NSURLSessionDataDelegate>

@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 - <NSURLSessionDataDelegate>
/**
 * 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 () <NSURLSessionDataDelegate>
/** 下载任务 */
@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 - <NSURLSessionDataDelegate>
/**
 * 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 () <NSURLSessionDownloadDelegate>
/** 下载任务 */
@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 - <NSURLSessionDownloadDelegate>
- (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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容