HTTP からファイルをダウンロードして、ローカルに保存する方法
// HTTP からファイルをダウンロードして、ローカルに保存、ローカルにファイルが存在すれば、ローカルのファイルをロード
//====================================================================================
- (void)loadImageFromRemote { // 読み込むファイルの URL を作成 // NSURL *url = [NSURL URLWithString:@"http://snippets.feb19.jp/wp-content/uploads/2013/01/Icon@2x.png"]; NSURL *url = [NSURL URLWithString:@"http://ringflow.jp/wp-content/themes/u-design/assets/product1/ipod-1.jpg"]; // 別のスレッドでファイル読み込みをキューに加える 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:@"ipod-1.jpg"]; 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]; }
- (IBAction)startDownLoad:(id)sender { // HTTP からファイルをダウンロードして、ローカルに保存、ローカルにファイルが存在すれば、ローカルのファイルをロード //実行処理 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"ipod-1.jpg"]; 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]; } }
【参考】
Objective-C (iOS): ウェブの画像をダウンロードして表示 | snippets.feb19.jp - http://snippets.feb19.jp/?p=410
以上、くまもんのグッズを爪切りを含めて色々持っている堀でした。