NSURLSession简单介绍

1,NSURLSession

NSURLSession,sharedSession是一个全局共享的单例,苹果为了方便程序员使用简单的网络任务

session发起下载任务,URLSession,所有的任务都是由session发起的

<span style="font-size:14px;">    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession]  downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
       
    }];
   
    // 所有的任务,默认都是挂起的,需要resume
    [task resume];</span>



2,NSURLSessionConfiguration

每一个NSURLSession对象都可以设置不同的NSURLSessionConfiguration,从而满足应用内不同类型的网络请求,NSURLSessionConfiguration的三种类型:

  - defaultSessionConfiguration

 默认session配置,类似NSURLConnection的标准配置,使用硬盘来存储缓存数据。

  - ephemeralSessionConfiguration

临时session配置,与默认配置相比,这个配置不会将缓存、cookie等存在本地,只会存在内存里,所以当程序退出时,所有的数据都会消失。

  - backgroundSessionConfiguration

后台session配置,与默认配置类似,不同的是会在后台开启另一个线程来处理网络数据。



3,NSURLSession下载代理方法

<span style="font-size:14px;">/** 下载完成 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"下载完成 %@", location);
}

/** 断点续传使用 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    // 什么也不写
}

/**
 bytesWritten                   本次下载的字节数
 totalBytesWritten              已经下载的字节数
 totalBytesExpectedToWrite      下载文件总字节数
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    // 进度 = 已经下载 / 总大小
    float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
   
    NSLog(@"%f %@", progress, [NSThread currentThread]);
   
    // 主线程更新UI GCD
//    dispatch_async(dispatch_get_main_queue(), ^ { self.progressView.progress = progress;});
    // NSOperation
    [[NSOperationQueue mainQueue] addOperationWithBlock: ^ { self.pView.progress = progress; }];
}</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值