0

我正在构建一个带有屏幕截图按钮的应用程序。现在,我想将在此应用中制作的所有屏幕截图保存在相同的自定义名称应用相册中。我已经知道如何在第一次使用下面的代码打开该应用程序时创建相册。我正在使用照片框架创建我的相册,例如:

-(void)createAppAlbum
{

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"App Album Name"];
    albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection;

}

 completionHandler:^(BOOL success, NSError *error) {
                         if (success) {
                         fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[albumPlaceholder.localIdentifier] options:nil];
                                          assetCollection = fetchResult.firstObject;

} 
                        else {
                              NSLog(@"Error creating album: %@", error);}
                                  }];

}

所以我的应用程序创建了名为“应用程序专辑名称”的专辑。我可以使用以下按钮将我的屏幕截图存储在我的新专辑中:

 -(IBAction)screenshot:(id)sender
{

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.view.bounds.size);

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

    PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
    [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
} completionHandler:^(BOOL success, NSError *error) {
    if (!success) {
        NSLog(@"Error creating asset: %@", error);
    }
}];

}

万一我离开这个viewController,然后再回来,我想找到我已经创建的相册,并在同一个相册中保存另一个屏幕截图,因为我不想每次进入这个视图控制器时都创建一个新的。

所以我的问题是,我如何获得我第一次按名称创建的专辑,然后保存新的屏幕截图。

4

1 回答 1

0

由于此问题专门针对 iOS 8,因此此代码可以正常工作:

- (void)saveImage:(UIImage *)image {
    if (!self.library) {
        self.library = [[ALAssetsLibrary alloc] init];
    }

    __weak ALAssetsLibrary *lib = self.library;

    [self.library addAssetsGroupAlbumWithName:@"My Photo Album" resultBlock:^(ALAssetsGroup *group) {

        ///checks if group previously created
        if(group == nil){

            //enumerate albums
            [lib enumerateGroupsWithTypes:ALAssetsGroupAlbum
                               usingBlock:^(ALAssetsGroup *g, BOOL *stop)
             {
                 //if the album is equal to our album
                 if ([[g valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"My Photo Album"]) {

                     //save image
                     [lib writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil
                                           completionBlock:^(NSURL *assetURL, NSError *error) {

                                               //then get the image asseturl
                                               [lib assetForURL:assetURL
                                                    resultBlock:^(ALAsset *asset) {
                                                        //put it into our album
                                                        [g addAsset:asset];
                                                    } failureBlock:^(NSError *error) {

                                                    }];
                                           }];

                 }
             }failureBlock:^(NSError *error){

             }];

        }else{
            // save image directly to library
            [lib writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil
                                  completionBlock:^(NSURL *assetURL, NSError *error) {

                                      [lib assetForURL:assetURL
                                           resultBlock:^(ALAsset *asset) {

                                               [group addAsset:asset];

                                           } failureBlock:^(NSError *error) {

                                           }];
                                  }];
        }

    } failureBlock:^(NSError *error) {

    }];
}

为了测试它是否有效,我创建了一个单屏应用程序,向视图添加了一个按钮,并添加了一个获取屏幕截图然后将图像传递给saveImage:函数的方法。这是我添加到它以使其工作的代码:

#import <AssetsLibrary/AssetsLibrary.h>

@interface ViewController ()
@property (nonatomic, strong) UIButton *screenshotButton;
@property (nonatomic, strong) ALAssetsLibrary *library;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.view addSubview:self.screenshotButton];
}

- (UIButton *)screenshotButton {
    if (!_screenshotButton) {
        _screenshotButton = [[UIButton alloc] initWithFrame:CGRectInset(self.view.bounds, 100.0f, 120.0f)];
        _screenshotButton.layer.borderColor = [UIColor blueColor].CGColor;
        _screenshotButton.layer.borderWidth = 2.0f;
        _screenshotButton.layer.cornerRadius = 5.0f;
        [_screenshotButton setTitle:@"Take Screenshot" forState:UIControlStateNormal];
        [_screenshotButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_screenshotButton addTarget:self action:@selector(takeScreenshot) forControlEvents:UIControlEventTouchUpInside];
    }

    return _screenshotButton;
}

- (void)takeScreenshot {
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(self.view.bounds.size);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * imgData = UIImagePNGRepresentation(image);
    if(imgData)
        [imgData writeToFile:@"screenshot.png" atomically:YES];
    else
        NSLog(@"error while taking screenshot");


    UIColor *randomColor = [UIColor colorWithHue:((CGFloat)(arc4random()%255)/255.0f)
                                      saturation:((CGFloat)(arc4random()%255)/200.0f)
                                      brightness:((CGFloat)(arc4random()%100)/255.0f) + 0.5f
                                           alpha:1.0f];
    self.screenshotButton.layer.borderColor = randomColor.CGColor;
    [self.screenshotButton setTitleColor:randomColor forState:UIControlStateNormal];

    [self saveImage:image];
}

需要注意的几点:

  • AssetsLibrary在 iOS 9 中已弃用,因此不建议在 iOS 8 之后使用,但仍然可以使用。
  • 这可以与任何UIImage传递的 to一起实现和使用saveImage:,因此即使您使用另一个库也可以工作。
  • 确保包括#import <AssetsLibrary/AssetsLibrary.h>.
  • 将“我的相册”更改为正确的相册名称,并可能静态设置
于 2015-10-13T20:17:50.500 回答