美文网首页
NSURLSessionDownloadTask

NSURLSessionDownloadTask

作者: lltree | 来源:发表于2017-09-22 15:20 被阅读26次
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"I'm Hear");
    //1 创建URL回话配置
    NSURLSessionConfiguration *cfg=[NSURLSessionConfiguration defaultSessionConfiguration];
    //2 创建带配置的URL会话
    NSURLSession *session=[NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    //3 创建下载任务/Users/smartlei/Sites/头像.jpg
    NSURL *url=[NSURL URLWithString:@"http://127.0.0.1/Xcode_7.0.1.dmg"];
//    NSURLRequest *request=[NSURLRequest requestWithURL:url];
//    NSURLSessionDownloadTask *task=[session downloadTaskWithRequest:request];
    NSURLSessionDownloadTask *task=[session downloadTaskWithURL:url];
    
    //4 开启任务
    [task resume];
}
#pragma NSURLSessionDownloadDelegate
//下载完成
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //下载完成后系统会在沙盒中保存个临时文件,如果不保存执行完沙盒自动清除
    [[NSFileManager defaultManager] copyItemAtPath:location.path toPath:@"/Users/smartlei/Desktop/qq.dmg" error:NULL];
}
//监听下载进度的方法
//bytesWritten:本次写入了多少字节
//totalBytesWritten:总共写入多少字节
//totalBytesExpectedToWrite:期望一共写入多少字节
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    CGFloat progress=(float)totalBytesWritten/totalBytesExpectedToWrite;
     NSLog(@"下载进度:%lf,线程:%@",progress,[NSThread currentThread]);
    dispatch_async(dispatch_get_main_queue(), ^{
        //主队列中更新进度
        self.progressView.progress=progress;
    });
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
    
}


相关文章

网友评论

      本文标题:NSURLSessionDownloadTask

      本文链接:https://www.haomeiwen.com/subject/qcsfextx.html