始终将屏幕截图保存在 "Photos" 中相同的自定义名称应用相册中

Always save screenshot in same custom name app album in "Photos"

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

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

}

所以我的应用创建了名为 "App Album Name" 的相册。 我可以使用如下按钮将屏幕截图存储在我的新相册中:

 -(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,稍后再回来,我想找到我已经创建的相册,并在同一个相册中保存另一个屏幕截图,因为我不想创建新的每次我进入这个视图控制器时。

所以我的问题是,我如何通过名称获取我第一次创建的相册,然后将新的屏幕截图保存在其中。

由于这个问题是专门针对iOS8,这段代码可以正常工作:

- (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 之后使用,但仍然有效。
  • 这可以实现并且 与传递给 saveImage: 的任何 UIImage 一起使用,因此它甚至可以工作 如果您正在使用另一个图书馆。
  • 确保包含 #import <AssetsLibrary/AssetsLibrary.h>.
  • 将 "My Photo Album" 更改为正确的相册名称,并可能对其进行静态设置