zoukankan      html  css  js  c++  java
  • iOS 学习

    使用NSURLSessionDownloadTask下载文件的过程与前面差不多,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中。

    //
    //  ViewController.m
    //  NSURLSession
    //
    //  Copyright © 2016年 asamu. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [self downLoadFile];
    }
    
    -(void)downLoadFile{
    //1.创建 url
        NSString *fileName = @"1.jpg";
        NSString *urlStr = [NSString stringWithFormat:@"http://img3.douban.com/lpic/s4717862.jpg",fileName];
        urlStr  = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlStr];
        //2.创建请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        //创建会话
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if(!error){
            //location 是下载后的临时保存路径,需要将它移动到需要保存的位置
            NSError *saveError = nil;
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            NSString *savePath = [cachePath stringByAppendingString:fileName];
            NSLog(@"%@",savePath);
            NSURL *url = [NSURL fileURLWithPath:savePath];
            
            [[NSFileManager defaultManager]copyItemAtURL:location toURL:url error:&saveError];
            if (!saveError) {
                NSLog(@"save success");
            }else{
                NSLog(@"error is :%@",saveError.localizedDescription);
            }
            }else{
                NSLog(@"error is :%@",error.localizedDescription);
            }
        }];
        //执行任务
        [downloadTask resume];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    @end
  • 相关阅读:
    crash reporting system for Windows applications
    1
    qt 试用 (3)配置编译源代码及调试
    kd tree & ray tracing
    new
    KMP算法中关于next数组的探究
    teamviewer vs echovnc
    NAT之stun确定nat类型
    Wireshark
    GNU httptunnel,当SSH被block时的选择
  • 原文地址:https://www.cnblogs.com/asamu/p/5423153.html
Copyright © 2011-2022 走看看