如何从URL下载照片并使用Objective-C for iOS8 +添加到特定相册中?

时间:2015-03-05 14:15:31

标签: ios objective-c alassetslibrary

我想从此网址http://placehold.it/200x200下载图片并添加到iOS上的特定相册照片中。 我花了好几个小时与ALAssetsLibrary合作但无法使其正常工作......这是我的代码:

// 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];
[...]

输出错误是:

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"}

ALAssetsLibrary有多个版本在线,但我使用的是最后一个版本。关于ALAssetsLibrary的使用有a great tutorial,但它已经过时了(iOS5)。不知道iOS8上是否仍然支持它。任何人都可以帮我下载图像并将其保存到特定的相册中吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

这应该有效:

 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) {}];