iOS --URLSession请求方法,以及文件下载
来源:互联网 发布:土建预算软件下载 编辑:程序博客网 时间:2024/06/04 00:20
1主要包含三个请求方法:NSURLSessionDataTask,NSURLSessionDownloadTask,NSURLSessionUploadTask。
2.第一种请求方法 --GET
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg"];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *_Nullable data,NSURLResponse *_Nullable response,NSError * _Nullable error) {
[selfshowImage:data];
NSLog(@"%@",data);
}];
[task resume];
}
-(void)showImage:(NSData *)data{
_imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(10,5,100,100)];
_imageView.image = [UIImageimageWithData:data];
[self.viewaddSubview:_imageView];
}
3.第二种请求方法,如果要设置请求头就得创建Request。---GET
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDataTask *dataTask = [sessiondataTaskWithURL:[NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg" ]completionHandler:^(NSData *_Nullable data,NSURLResponse *_Nullable response,NSError * _Nullable error) {
[self showImage:data];
}];
[dataTask resume];
4.第三种请求方法 -- POSTNSURL *url = [NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg"];
NSURLSession *session = [NSURLSessionsharedSession];
NSMutableURLRequest *request = [NSURLRequestrequestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=123&ped=123"dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionDataTask *dataTask = [sessiondataTaskWithRequest:requestcompletionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
NSLog(@"%@",data);
}];
[dataTask resume];
5.文件下载:默认存储在temp,需要手动存储在沙盒NSURL *url = [NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg"];
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDownloadTask *sessionTask = [sessiondownloadTaskWithURL:urlcompletionHandler:^(NSURL *_Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"-------ok!");
//剪切location的临时文件到真实位置
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:response.suggestedFilename];
NSFileManager *mgr = [NSFileManagerdefaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:
nil];
}];
[sessionTask resume];
6.代理NSURLSessionDelegate-(void)download1{
NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]delegate:selfdelegateQueue:[[NSOperationQueuealloc]init]];
NSURLSessionDataTask *task = [sessiondataTaskWithRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@""]]];
[task resume];
[task cancel];
[task suspend];
}
//接受到服务器的数据,可能会被多次调用。
-(void)URLSession:(NSURLSession *)session dataTask:(nonnullNSURLSessionDataTask *)dataTask didReceiveData:(nonnullNSData *)data{
}
//接收服务器的响应
-(void)URLSession:(NSURLSession *)session dataTask:(nonnullNSURLSessionDataTask *)dataTask didReceiveResponse:(nonnullNSURLResponse *)response completionHandler:(nonnullvoid (^)(NSURLSessionResponseDisposition))completionHandler{
//允许服务器的响应,才会继续接受服务器返回
completionHandler(NSURLSessionResponseAllow);
/**
* 补充NSUrlSessionTask创建的任务
*
* Task可以暂停盒挂起。
*/
}
//请求完毕,成功/失败。
-(void)URLSession:(NSURLSession *)session task:(nonnullNSURLSessionTask *)task didCompleteWithError:(nullableNSError *)error{
}
7.注意点,只要是NSURLSessionTask创建的任务Task,就可以:
-(void)suspend;//暂停
-(void)cancel;//取消
-(void)resume;//恢复
@property(readonly,copy)NSError *error;//错误
@property(readonly,copy)NSURLResponse *response;//响应
8.大文件下载
-(void)downLoadBigFile{
NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]delegate:selfdelegateQueue:[[NSOperationQueuealloc]init]];
NSURLSessionDownloadTask *downloadTask = [sessiondownloadTaskWithURL:[NSURLURLWithString:@""]];
[downloadTask resume];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}
//每当写入临时文件时就会调用
/**
* <#Description#>
*
* @param session <#session description#>
* @param downloadTask <#downloadTask description#>
* @param bytesWritten 这次写入
* @param totalBytesWritten 文件已写入
* @param totalBytesExpectedToWrite 文件总大小
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float progress = 1 * totalBytesWritten / totalBytesExpectedToWrite;
}
//下载完毕就会调用这个方法。
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *mgr = [NSFileManagerdefaultManager];
[mgr moveItemAtURL:locationtoURL:[NSURLfileURLWithPath:file]error:nil];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}
9.断电下载:思路
-(NSURLSession *)session{
if (_session ==nil) {
_session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]delegate:selfdelegateQueue:[[NSOperationQueuealloc]init]];
}
return _session;
}
#define WCY [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"resumeData.temp" ]
-(NSData *)resumeData{
if (_resumeData ==nil) {
_resumeData = [NSDatadataWithContentsOfFile:WCY];
}
return_resumeData;
}
- (IBAction)Start:(id)sender {
if (self.resumeData) {
self.downloadTask = [_sessiondownloadTaskWithResumeData:self.resumeData];
}else{
_downloadTask = [_sessiondownloadTaskWithURL:[NSURLURLWithString:@""]];
}
[_downloadTaskresume];
}
- (IBAction)Pause:(id)sender {
// [_downloadTask suspend];
[_downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
/**
* rsumrData:记录上次下载的信息。
*/
self.resumeData = resumeData;
// 可以将上一次保存的数据写入沙盒保存。
[resumeData writeToFile:WCYatomically:YES];
// 缓存空间
NSString *tmp = NSTemporaryDirectory();
}];
}
- (IBAction)GoOn:(id)sender {
self.downloadTask = [self.sessiondownloadTaskWithResumeData:self.resumeData];
[_downloadTask resume];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}
//每当写入临时文件时就会调用
/**
* <#Description#>
*
* @param session <#session description#>
* @param downloadTask <#downloadTask description#>
* @param bytesWritten 这次写入
* @param totalBytesWritten 文件已写入
* @param totalBytesExpectedToWrite 文件总大小
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float progress = 1 * totalBytesWritten / totalBytesExpectedToWrite;
}
//下载完毕就会调用这个方法。
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *mgr = [NSFileManagerdefaultManager];
[mgr moveItemAtURL:locationtoURL:[NSURLfileURLWithPath:file]error:nil];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}
[[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"www"]]setValue:@"10234"forHTTPHeaderField:@"Range"];
11.如果非正常下载失败,在下面的方法中保存数据。
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
// 如果因为其他原因失败,保存resumeData
self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}
- (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cfg = [NSURLSessionConfigurationdefaultSessionConfiguration];
cfg.timeoutIntervalForRequest =10;
// 是否允许使用蜂窝网络(手机自带网络)
cfg.allowsCellularAccess =YES;
_session = [NSURLSessionsessionWithConfiguration:cfg];
}
return_session;
}
- (void)viewDidLoad {
[superviewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"http://120.25.226.186:32812/upload"]];
request.HTTPMethod = @"POST";
// 设置请求头(告诉服务器,这是一个文件上传的请求)
[request setValue:[NSStringstringWithFormat:@"multipart/form-data; boundary=%@",WCYBoundary]forHTTPHeaderField:@"Content-Type"];
// 设置请求体
NSMutableData *body = [NSMutableDatadata];
// 文件参数
// 分割线
[body appendData:WCYEncode(@"--")];
[body appendData:WCYEncode(WCYBoundary)];
[body appendData:WCYNewLine];
// 文件参数名
[body appendData:WCYEncode([NSStringstringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:WCYNewLine];
// 文件的类型
[body appendData:WCYEncode([NSStringstringWithFormat:@"Content-Type: image/png"])];
[body appendData:WCYNewLine];
// 文件数据
[body appendData:WCYNewLine];
[body appendData:[NSDatadataWithContentsOfFile:@"/Users/Desktop/test.png"]];
[body appendData:WCYNewLine];
// 结束标记
/*
--分割线--\r\n
*/
[body appendData:WCYEncode(@"--")];
[body appendData:WCYEncode(WCYBoundary)];
[body appendData:WCYEncode(@"--")];
[body appendData:WCYNewLine];
[[self.sessionuploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data,NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil]);
}] resume];
}
- iOS --URLSession请求方法,以及文件下载
- iOS开发-URLSession使用-URLSession网络请求
- URLSession 下载以及注意点
- iOS开发-使用AFN实现GET/POST请求,以及文件下载/文件(图片)上传
- urlsession 与后台下载
- iOS中的URLSession
- URLSession数据协议下载图片
- URLSession 后台多任务下载
- 基于Swift的iOS应用程序开发:使用URLSession向服务器发送请求
- iOS NSURLSession 实现网络请求-文件下载-上传-后台下载
- iOS 对于下载请求超时重新下载的方法
- iOS开发 ----- 网络请求4 ----- 下载数据以及断点续传
- URLSession
- URLSession
- springmvc下载文件以及下载大文件方法
- springmvc下载文件以及下载大文件方法
- springmvc下载文件以及下载大文件方法
- Networking with URLSession二 上传&下载
- android 常见分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕适配注意事项
- linux下的jenkins+git+maven+github组合使用
- mysql莫名其妙不支持批处理(batch)的解决办法
- python package概念
- 士兵杀敌(三)
- iOS --URLSession请求方法,以及文件下载
- 数据库CRUD的通用方法
- android 自定义的dialog
- 【Spring】【笔记】《Spring In Action》第6章 事务管理
- Android studio找不到HttpClient的问题
- Scala中常见的容器 元组 Tuple
- EasyUI的window加载的页面不执行js问题说明
- 互联网时代,我所期待的服务
- 【JAVA】接口