If you are using iOS6, Fernando's answer will not work, because the saveImage selector is no longer available.
The process is pretty confusing, and I have not seen any clear answers posted, so here is the method I've used to solve this in iOS6.
You will need to use a combination of the following:
Create the Album:
[self.library addAssetsGroupAlbumWithName:albumName
resultBlock:^(ALAssetsGroup *group) {
NSLog(@"added album:%@", albumName);
}
failureBlock:^(NSError *error) {
NSLog(@"error adding album");
}];
Find the Album:
__block ALAssetsGroup* groupToAddTo;
[self.library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:albumName]) {
NSLog(@"found album %@", albumName);
groupToAddTo = group;
}
}
failureBlock:^(NSError* error) {
NSLog(@"failed to enumerate albums:
Error: %@", [error localizedDescription]);
}];
Save the Image to Asset Library, and put it into the album:
CGImageRef img = [image CGImage];
[self.library writeImageToSavedPhotosAlbum:img
metadata:[info objectForKey:UIImagePickerControllerMediaMetadata]
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
NSLog(@"saved image completed:
url: %@", assetURL);
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[groupToAddTo addAsset:asset];
NSLog(@"Added %@ to %@", [[asset defaultRepresentation] filename], albumName);
}
failureBlock:^(NSError* error) {
NSLog(@"failed to retrieve image asset:
Error: %@ ", [error localizedDescription]);
}];
}
else {
NSLog(@"saved image failed.
error code %i
%@", error.code, [error localizedDescription]);
}
}];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…