我正在尝试在iPhone的照片库中创建自定义相册,然后保存我用相机拍摄的照片,或从手机相机胶卷中选择到该自定义相册的照片。我可以成功创建相册,但照片没有保存在那里,而是保存到模拟器保存的照片相册...我不知道如何告诉UIImageWriteToSavedPhotosAlbum
保存到新专辑我'我刚刚使用addAssetsGroupAlbumWithName
...
这是我到目前为止的代码 - 我已经删除了几个部分以保持我的代码示例简短......
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage])
{
// pull GPS information from photos metadata using ALAssetsLibrary
void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset)
{
// code snipped out
};
NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:assetURL
resultBlock:ALAssetsLibraryAssetForURLResultBlock
failureBlock:^(NSError *error)
{
// code snipped out
}];
// getimage from imagePicker and resize it to the max size of the iPhone screen
UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *resizedImage = [util_ createThumbnailForImage:originalImage thumbnailSize:[util_ determineIPhoneScreenSize]];
NSData *imageData = UIImagePNGRepresentation(resizedImage);
// code snipped out
// code snipped out
// code snipped out
// code snipped out
// code snipped out
// code snipped out
// create a new album called "My Apps Photos"
[library addAssetsGroupAlbumWithName:@"My Apps Photos"
resultBlock:^(ALAssetsGroup *group)
{
NSLog(@"in addAssetsGroupAlbumWithName resultBlock");
// save file to album
UIImageWriteToSavedPhotosAlbum(resizedImage, self, nil, nil);
}
failureBlock:^(NSError *error)
{
NSLog(@"in addAssetsGroupAlbumWithName failureBlock");
}
];
}
}
所以...就像我说的那样,它创造了新专辑,但没有将照片保存在那里。如何告诉它保存到新专辑中?也许我听不到使用UIImageWriteToSavedPhotosAlbum
??
注意:我正在使用Xcode 4.3.2,IOS 5.1和ARC
答案 0 :(得分:59)
如果您使用的是iOS6,Fernando的答案将无效,因为saveImage选择器不再可用。
这个过程非常令人困惑,我没有看到任何明确的答案,所以这是我在iOS6中用来解决这个问题的方法。
您需要结合使用以下内容:
创建相册:
[self.library addAssetsGroupAlbumWithName:albumName
resultBlock:^(ALAssetsGroup *group) {
NSLog(@"added album:%@", albumName);
}
failureBlock:^(NSError *error) {
NSLog(@"error adding 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:\nError: %@", [error localizedDescription]);
}];
将图片保存到资源库,并将其放入相册:
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:\nurl: %@", 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:\nError: %@ ", [error localizedDescription]);
}];
}
else {
NSLog(@"saved image failed.\nerror code %i\n%@", error.code, [error localizedDescription]);
}
}];
答案 1 :(得分:11)
费尔南多的回答在iOS 7中对我有用。
步骤:
1)从此处下载ALAssetsLibrary + CustomPhotoAlbum代码:http://www.touch-code-magazine.com/wp-content/uploads/2011/11/ALAssetsLibrary_CustomPhotoAlbum.zip?a071b6并复制Xcode项目中类别的2个文件。
2)在头文件中,添加以下行
#import <AssetsLibrary/AssetsLibrary.h>
#import "ALAssetsLibrary+CustomPhotoAlbum.h"
@property (strong, atomic) ALAssetsLibrary* library;
3)在您的实施文件中,添加以下行
@synthesize library=_library;
编辑:4)初始化资产库实例,最好是“viewDidLoad”方法,否则下面的saveImage方法将不会执行。 (确认):
[我正在重新提交建议的编辑,因为有非iphone技能的人拒绝了之前的提交。这对@santhu&amp; amp;答案来说无疑是一个很好的答案。费尔南多给了我很多帮助,然而,初始化的代码片段丢失了所以我花了一些时间来弄清楚为什么代码不起作用。因此,如果具有iPhone开发技能的主持人审核编辑,我将不胜感激。]
_library = [[ALAssetsLibrary alloc] init];
5)在您要保存的方法中添加
//Add this in the method where you wish to save
[self.library saveImage:(UIImage *) toAlbum:(NSString *) withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(@"Big error: %@", [error description]);
}
}];
答案 2 :(得分:9)
对于快速用户: - 我做了同样的事情。
声明闭包大写类定义(上面的类定义)
typealias CompletionHandler = (success:Bool!) -> Void
在类
中声明库变量var library:ALAssetsLibrary?;
在viewDidLoad中初始化变量
library = ALAssetsLibrary();
将图像添加到特定相册的方法
func addImage(image:UIImage, metaData:NSDictionary, toAlbum albumName:String, handler:CompletionHandler){
library?.addAssetsGroupAlbumWithName(albumName, resultBlock: {(group:ALAssetsGroup!) -> Void in
print("\nAlbum Created:= \(albumName)");
/*-- Find Group --*/
var groupToAddTo:ALAssetsGroup?;
self.library?.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupAlbum),
usingBlock: { (group:ALAssetsGroup?, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
if(group != nil){
if group!.valueForProperty(ALAssetsGroupPropertyName) as String == albumName{
groupToAddTo = group;
print("\nGroup Found \(group!.valueForProperty(ALAssetsGroupPropertyName))\n");
self.library?.writeImageToSavedPhotosAlbum(image.CGImage, metadata:metaData, completionBlock: {(assetURL:NSURL!,error:NSError!) -> Void in
if(error == nil){
self.library?.assetForURL(assetURL,
resultBlock: { (asset:ALAsset!) -> Void in
var yes:Bool? = groupToAddTo?.addAsset(asset);
if (yes == true){
handler(success: true);
}
},
failureBlock: { (error2:NSError!) -> Void in
print("Failed to add asset");
handler(success: false);
});
}
});
}
} /*Group Is Not nil*/
},
failureBlock: { (error:NSError!) -> Void in
print("Failed to find group");
handler(success: false);
});
}, failureBlock: { (error:NSError!) -> Void in
print("Failed to create \(error)");
handler(success: false);
});
}
将此方法称为: -
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
var image:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage;
var metadata:NSDictionary = info[UIImagePickerControllerMediaMetadata] as NSDictionary;
self.addImage(image, metaData: metadata, toAlbum: "SwiftAlbum") { (success) -> Void in
print("Image Added : \(success)");
}
picker.dismissViewControllerAnimated(true, completion: nil);
}
答案 3 :(得分:3)
来自@Scott Allen的代码很接近但不会第一次为我保存图像。因此,如果我没有创建相册,图像将无法保存。我的解决方案是将创建相册的片段移动到app delegate didFinishLaunchingWithOptions:
NSString *albumName=@"album name";
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:albumName
resultBlock:^(ALAssetsGroup *group) {
NSLog(@"added album:%@", albumName);
}
failureBlock:^(NSError *error) {
NSLog(@"error adding album");
}];
答案 4 :(得分:2)
我还没有看到这些问题的答案和代码。对我来说,我想确保在我启动相机之前找到或创建相册。这段代码似乎是正确的,我认为它更清洁,更容易从中偷取^ H ^ H ^ H ^ H ^ Hstart。
// find or create our photo album. If either works
// we fire up the camera. Crazy asynchronous code here.
__weak PhotoVC *weakSelf = self;
__block BOOL found = NO;
ALAssetsLibraryGroupsEnumerationResultsBlock
assetGroupEnumerator = ^(ALAssetsGroup *group, BOOL *stop){
if (group) {
NSString *thisGroup = [group valueForProperty:ALAssetsGroupPropertyName];
if ([album isEqualToString:thisGroup]) {
NSLog(@"album found!");
[weakSelf startCamera: group];
*stop = YES;
found = YES;
}
} else { // not found, create the album
if (found)
return;
NSLog(@"album not found, try making album");
ALAssetsLibraryGroupResultBlock addGroup =
^(ALAssetsGroup *group){
NSLog(@"album created");
[weakSelf startCamera: group];
};
ALAssetsLibraryAccessFailureBlock addGroupFailed =
^(NSError *err){
NSLog(@"add group failed: %@", [err localizedDescription]);
};
[library addAssetsGroupAlbumWithName:album resultBlock:addGroup failureBlock:addGroupFailed];
}
};
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {
NSLog(@"album access denied");
}];
Tom Duff定律:尽可能地窃取代码。