网络:NSURLSession 上传文件和代理的选择
来源:互联网 发布:牛群 冯巩 知乎 编辑:程序博客网 时间:2024/06/07 22:32
#import "ViewController.h"#define CZBoundary @"itcast"// NSURLSessionDataDelegate 接收服务器返回的数据// NSURLSessionTaskDelegate -> NSURLSessionDelegate 上传进度以及HTTPS相当的代理// NSURLSessionDownloadDaskDelegate 下载进度@interface ViewController ()<NSURLSessionTaskDelegate,NSURLSessionDataDelegate>@property (weak, nonatomic) IBOutlet UIProgressView *progressView;@property (nonatomic, strong) NSURLSession *session; // 自定义会话@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ // NSURL NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload.php"]; // 创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // http请求方法使用POST [request setHTTPMethod:@"POST"]; // 告诉服务器我是上传二进制数据 [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",CZBoundary] forHTTPHeaderField:@"Content-Type"]; // 图片路径 NSString *path = [[NSBundle mainBundle] pathForResource:@"01.mp4" ofType:nil]; // 图片数据 NSData *imageData = [NSData dataWithContentsOfFile:path]; // 拼接好的二进制数据 NSData *uploadData = [self dataWithFileData:imageData fieldName:@"userfile" fileName:@"abc.mp4"]; // 不使用block让代理返回进度 [[self.session uploadTaskWithRequest:request fromData:uploadData]resume];}// 上传进度- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { CGFloat progress = (CGFloat)totalBytesSent / totalBytesExpectedToSend; NSLog(@"%f",progress); // 回到主线程刷新UI dispatch_async(dispatch_get_main_queue(),^{ self.progressView.progress = progress; });}// 接收到数据- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"接收到数据%zd",data.length);//{}}// 完成了- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"完成了");}- (void)uploadData { // NSURL NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload.php"]; // 创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // http请求方法使用POST [request setHTTPMethod:@"POST"]; // 告诉服务器我是上传二进制数据 [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",CZBoundary] forHTTPHeaderField:@"Content-Type"]; // 图片路径 NSString *path = [[NSBundle mainBundle] pathForResource:@"image.png" ofType:nil]; // 图片数据 NSData *imageData = [NSData dataWithContentsOfFile:path]; // 拼接好的二进制数据 NSData *uploadData = [self dataWithFileData:imageData fieldName:@"userfile" fileName:@"abc.png"]; [[[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:uploadData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@ -- %@",response,[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]); }] resume];}/** 返回上传需要的二进制数据 1. 文件的数据 2. 后台给的字段名 3. 上传的文件名 */- (NSData *)dataWithFileData:(NSData *)fileData fieldName:(NSString *)fieldName fileName:(NSString *)fileName { // 可变的二进制数据 NSMutableData *dataM = [NSMutableData data]; // 可变字符串用来拼接数据 NSMutableString *strM = [NSMutableString stringWithFormat:@"--%@\r\n",CZBoundary]; [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\" \r\n",fieldName,fileName]; // application/octet-stream 代表上传所有的二进制格式都支持 [strM appendString:@"Content-Type: application/octet-stream \r\n\r\n"]; // NSLog(@"%@",strM); // 把前面一部份数据先拼接 [dataM appendData:[strM dataUsingEncoding:NSUTF8StringEncoding]]; // 拼接文件的二进制数据 [dataM appendData:fileData]; // 清空可变字符串之后,再设置内容为\r\n [strM setString:@"\r\n"]; [strM appendFormat:@"--%@--",CZBoundary]; // 把最后一部份加到二进制数据中 [dataM appendData:[strM dataUsingEncoding:NSUTF8StringEncoding]]; // NSLog(@"%@",strM); return dataM.copy;}- (NSURLSession *)session { if (_session == nil) { _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; } return _session;}@end
0 0
- 网络:NSURLSession 上传文件和代理的选择
- [iOS]网络之NSURLSession的文件上传
- IOS学习 网络 NSURLSession和POST文件上传
- NSURLSession的上传和下载
- 使用NSURLSession 实现单个文件的上传
- 使用NSURLSession 实现单个文件的上传
- NSURLSession文件上传
- NSURLSession 做文件上传
- iOS NSURLSession 实现网络请求-文件下载-上传-后台下载
- 关于NSURLSession的上传和下载
- 关于NSURLSession的上传和下载
- 关于 NSURLSession 的上传和下载
- 网络---大文件的下载(NSURLSession)
- [iOS]网络之NSURLSession的文件下载
- 网络:NSURLSession 下载文件
- NSURLSession参数、文件上传实例
- 使用NSURLSession,NSURLSessionUploadTask上传文件
- 网络:NSURLSession 的断点续传
- googleNet Inception v1 - v4 papers 发展历程
- Android开发:shape和selector和layer-list的(详细说明)
- APUE------进程环境
- 图像显著区域检测代码及其效果图 saliency region detection
- 屏幕适配
- 网络:NSURLSession 上传文件和代理的选择
- MongoDB简介与安装
- android jni开发
- Android笔记之用eclipse给zxing打jar包
- Android Bitmap换背景颜色
- Afinal 框架学习
- Rebar:Erlang构建工具(转载)
- 分治思想之快速排序
- 正确使用Java的foreach语句