Objective-C (iOS): ウェブの画像をダウンロードして表示

FileDownloadViewController

Objective-C: FileDownloadViewController.h

#import <UIKit/UIKit.h>

@interface FileDownloadViewController : UIViewController

@end

Objective-C: FileDownloadViewController.m

#import "FileDownloadViewController.h"

@interface FileDownloadViewController ()

@end

@implementation FileDownloadViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(50, 250, 220, 50);
    [button setTitle:@"File Download" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(fileDownloadButtonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)fileDownloadButtonWasTapped:(id)sender
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"icon.png"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:dataPath];
    if (success) {
        NSLog(@"load from local");
        NSData *data = [NSData dataWithContentsOfFile:dataPath];
        
        UIImage *image =  [[UIImage alloc] initWithData:data];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [self.view addSubview:imageView];
    } else {
        NSLog(@"load from remote");
        [self loadImageFromRemote];
    }
}

// HTTP からファイルをロード
- (void)loadImageFromRemote
{
    // 読み込むファイルの URL を作成
    NSURL *url = [NSURL URLWithString:@"http://snippets.feb19.jp/wp-content/uploads/2013/01/Icon@2x.png"];
    
    // 別のスレッドでファイル読み込みをキューに加える
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(loadImage:)
                                        object:url];
    [queue addOperation:operation];
}

// 別スレッドでファイルを読み込む
- (void)loadImage:(NSURL *)url
{
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:url];
    
    // 読み込んだらメインスレッドのメソッドを実行
    [self performSelectorOnMainThread:@selector(saveImage:) withObject:imageData waitUntilDone:NO];
}

// ローカルにデータを保存
- (void)saveImage:(NSData *)data
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"icon.png"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL success = [fileManager fileExistsAtPath:dataPath];
    if (success) {
        data = [NSData dataWithContentsOfFile:dataPath];
    } else {
        [data writeToFile:dataPath atomically:YES];
    }
    
    UIImage *image =  [[UIImage alloc] initWithData:data];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.view addSubview:imageView];
}

@end