本文共 2920 字,大约阅读时间需要 9 分钟。
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #ffffff}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #ffffff; min-height: 21.0px}p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px 'PingFang SC'; color: #4cbf57}p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #00afca}p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #4cbf57}p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #d28f5a}span.s1 {font-variant-ligatures: no-common-ligatures}span.s2 {font-variant-ligatures: no-common-ligatures; color: #c2349b}span.s3 {font-variant-ligatures: no-common-ligatures; color: #00afca}span.s4 {font-variant-ligatures: no-common-ligatures; color: #93c86a}span.s5 {font: 18.0px Menlo; font-variant-ligatures: no-common-ligatures; color: #ffffff}span.s6 {font: 18.0px Menlo; font-variant-ligatures: no-common-ligatures}span.s7 {font-variant-ligatures: no-common-ligatures; color: #ffffff}span.s8 {font: 18.0px 'PingFang SC'; font-variant-ligatures: no-common-ligatures}span.s9 {font-variant-ligatures: no-common-ligatures; color: #e44448}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self download];}-(void)download{ //获取NSURLSession的对象(为了获取下载进度,使用这个方法,执行代理方法,记得遵循代理方法) NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; //获取下载任务 NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@""]]; //启动下载任务 [task resume];}#pragma mark -- NSURLSessionDownloadDelegate代理方法 ---(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{}//继续下载-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{}/** * 正在下载(每当写入临时文件时就调用一次) * @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{}//下载完毕的时候调用一次-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ //文件将来存放的真是路径 NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //剪切文件到真是路径 NSFileManager *mager = [NSFileManager defaultManager]; [mager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil]; }复制代码
转载于:https://juejin.im/post/5a311bc7f265da4322413288