iOS --URLSession请求方法,以及文件下载

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.第三种请求方法 -- POST

        NSURL *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:request completionHandler:^(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:url completionHandler:^(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{

        

}


10.断电下载,调用的是请求头Response,

 [[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"www"]]setValue:@"10234" forHTTPHeaderField:@"Range"];


11.如果非正常下载失败,在下面的方法中保存数据。

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{

        

//        如果因为其他原因失败,保存resumeData

        self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];

        

}


12.文件的上传


- (NSURLSession *)session

{

    if (!_session) {

        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];

        cfg.timeoutIntervalForRequest = 10;

        // 是否允许使用蜂窝网络(手机自带网络)

        cfg.allowsCellularAccess = YES;

        _session = [NSURLSession sessionWithConfiguration:cfg];

    }

    return _session;

}


- (void)viewDidLoad {

    [super viewDidLoad];

    

}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];

    request.HTTPMethod = @"POST";

    

    // 设置请求头(告诉服务器,这是一个文件上传的请求)

    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", WCYBoundary] forHTTPHeaderField:@"Content-Type"];

    

    // 设置请求体

    NSMutableData *body = [NSMutableData data];

    

    // 文件参数

    // 分割线

    [body appendData:WCYEncode(@"--")];

    [body appendData:WCYEncode(WCYBoundary)];

    [body appendData:WCYNewLine];

    

    // 文件参数名

    [body appendData:WCYEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];

    [body appendData:WCYNewLine];

    

    // 文件的类型

    [body appendData:WCYEncode([NSString stringWithFormat:@"Content-Type: image/png"])];

    [body appendData:WCYNewLine];

    

    // 文件数据

    [body appendData:WCYNewLine];

    [body appendData:[NSData dataWithContentsOfFile:@"/Users/Desktop/test.png"]];

    [body appendData:WCYNewLine];

    

    // 结束标记

    /*

     --分割线--\r\n

     */

    [body appendData:WCYEncode(@"--")];

    [body appendData:WCYEncode(WCYBoundary)];

    [body appendData:WCYEncode(@"--")];

    [body appendData:WCYNewLine];

    

    [[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);

    }] resume];

}







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值