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
  • 相关阅读:
    Linux c++ time different
    数据库初始化以及制作为Windows服务
    数据库无法注册服务
    JS中String转int
    数据库服务注册(使用命令注册):解决my.ini配置文件不存在的问题
    数据库启动丢失MSVCP120.dll
    jQuery
    BOM和DOM
    用yield实现python协程
    深入理解python中的yield关键字
  • 原文地址:https://www.cnblogs.com/asamu/p/5423153.html
Copyright © 2011-2022 走看看