经常我们会把程序中的照片保存到指定相册中
保存到系统相册
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
}];
系统还提供了另外一些API
// With a UIImage, the API user can use -[UIImage CGImage] to get a CGImageRef, and cast -[UIImage imageOrientation] to ALAssetOrientation.
- (void)writeImageToSavedPhotosAlbum:(CGImageRef)imageRef orientation:(ALAssetOrientation)orientation completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock;
// The API user will have to specify the orientation key in the metadata dictionary to preserve the orientation of the image
- (void)writeImageToSavedPhotosAlbum:(CGImageRef)imageRef metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock
// If there is a conflict between the metadata in the image data and the metadata dictionary, the image data metadata values will be overwritten
- (void)writeImageDataToSavedPhotosAlbum:(NSData *)imageData metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock
保存到新建相册
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
if (error!=nil) {
return;
}
// 先枚举所有的相册组
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupLibrary usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// 如果已经有这个相册
if ([NewAlbum compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {
[assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[group addAsset:asset];
} failureBlock:^(NSError *error) {
}];
}
else {
// 如果没有这个相册
__weak ALAssetsLibrary *weakLibrary = assetsLibrary;
[weakLibrary addAssetsGroupAlbumWithName:NewAlbum resultBlock:^(ALAssetsGroup *group) {
// 保存到相册
[assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[group addAsset:asset];
} failureBlock:^(NSError *error) {
}];
} failureBlock:^(NSError *error) {
}];
}
} failureBlock:^(NSError *error) {
}];
}];
}