iOS-网络数据请求-异步图片下载

2016-03-01 16:01:00



//
// ViewController.m
// 网络数据请求-图片下载
//
// Created by YIem on 16/3/1.
// Copyright © 2016年 YIem. All rights reserved.
//

import "ViewController.h"

@interface ViewController ()
// 图片
@property (nonatomic, retain) UIImageView *imageV;
@end

@implementation ViewController

  • (void)dealloc
    {

    [_imageV release];
    [super dealloc];

    }

  • (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor cyanColor];
    UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeSystem];
    imageButton.frame = CGRectMake(100, 100, 100, 100);
    [imageButton setTitle:@"下载图片" forState:UIControlStateNormal];
    [imageButton addTarget:self action:@selector(imageAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:imageButton];
    
    self.imageV = [[UIImageView alloc] initWithFrame:CGRectMake(100, 200, 300, 200)];
    _imageV.backgroundColor = [UIColor redColor];
    [self.view addSubview:_imageV];
    [_imageV release];

    }

  • (void)imageAction
    {

    NSURL *url = [NSURL URLWithString:@"http://yiem.net/usr/uploads/2016/01/3648146106.jpg"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *dowImageTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 获取本地文件对应的路径
        NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        // 拼接文件的名字(系统建议的名字)
        NSString *file = [cach stringByAppendingPathComponent:response.suggestedFilename];
        NSFileManager *fileM = [NSFileManager defaultManager];
        // 将下载的数据由临时文件移动到本地路径
        [fileM moveItemAtPath:location.path toPath:file error:nil];
        // 就图片铺建显示
        _imageV.image = [UIImage imageWithContentsOfFile:file];
    }];
    // 开始任务
    [dowImageTask resume];

    }

  • (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

    }

@end

当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »