设为首页 加入收藏

TOP

iOS 学习 - 10下载(2) NSURLSession 图片 篇
2017-10-13 10:24:10 】 浏览:9239
Tags:iOS 学习 下载 NSURLSession 图片篇

使用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
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇AFN总结 下一篇分页(进行封装处理)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目