Reputation: 900
I would like to download the image from this URL http://placehold.it/200x200 and add into a specific album photo on iOS. I spent hours to work with ALAssetsLibrary but unable to get it working properly... Here is my code :
// ViewController.h
@property (strong, atomic) ALAssetsLibrary* library;
// ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.library = [[ALAssetsLibrary alloc] init];
}
- (void)viewDidUnload {
self.library = nil;
[super viewDidUnload];
}
[...]
NSURL *image_url = [NSURL URLWithString:@"http://placehold.it/200x200"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:image_url]];
void (^completion)(NSURL *, NSError *) = ^(NSURL *assetURL, NSError *error) {
if (error) NSLog(@"Error A : %@", [error description]);
};
void (^failure)(NSError *) = ^(NSError *error) {
if (error == nil) return;
NSLog(@"Error B : %@", [error description]);
};
[self.library saveImage:image toAlbum:@"Sample album" completion:completion failure:failure];
[...]
Output error are :
Connection to assetsd was interrupted or assetsd died
Error B : Error Domain=ALAssetsLibraryErrorDomain Code=-3300 "Write failed" UserInfo=0x7ff4da570ae0 {NSLocalizedFailureReason=There was a problem writing this asset because the write failed., NSLocalizedDescription=Write failed, NSUnderlyingError=0x7ff4da5709d0 "Write failed"}
There is multiple versions of ALAssetsLibrary online but I used the last one. There is a great tutorial about usage of ALAssetsLibrary but it's old (iOS5). Don't know if it's still supported correctly on iOS8. Can anyone help me to download an image and save it into a specific album please ? Thanks in advance.
Upvotes: 1
Views: 566
Reputation: 2073
This should work:
NSURL *image_url = [NSURL URLWithString:@"http://placehold.it/200x200"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:image_url]];
[self.library writeImageToSavedPhotosAlbum:image.CGImage orientation:0 completionBlock:^(NSURL *assetURL, NSError *error) {}];
Upvotes: 1