0

I am building an app with button that make screen shot. Now I want to save all screen shots made in this app, in same custom name app album. I already know how to create album just the first time that app opens with code bellow. I am creating my album with Photos framework like:

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

}

So my app creates album named "App Album Name". I am able to take and store my screenshot in my new album with button like:

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

}

In case I leave this viewController, and get back in later, I want to find album that I already created, and save another screen shot in same album, because I don't want to create new one every time I enter this view controller.

So my question is, how would I get album I created first time by Name and then save new screen shots in.

MOzeb
  • 423
  • 1
  • 6
  • 14
  • Possible duplicate of [iOS save photo in an app specific album](http://stackoverflow.com/questions/11972185/ios-save-photo-in-an-app-specific-album) – Fennelouski Oct 13 '15 at 19:54
  • @Fennelouski - iOS 5, and also not using Photo framework.. – MOzeb Oct 13 '15 at 19:57
  • Can you explain what the hard part is? When you create the album, you get its identifier. From then on, access the album by its identifier. What's the difficulty for you? – matt Oct 13 '15 at 20:20

1 Answers1

0

Since this question is specifically targeting, iOS 8, this code will work just fine:

- (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) {

    }];
}

To test that this works, I created a single screen application, added a button to the view, and added a method that takes a screenshot and then passes the image to the saveImage: function. Here's the code that I added to it to make it work:

#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];
}

A few things to note:

  • AssetsLibrary is deprecated in iOS 9, so it is not recommended to be used after iOS 8, but will still work.
  • This can be implemented and used with any UIImage passed to saveImage:, so it can work even if you're using another library.
  • Make sure to include #import <AssetsLibrary/AssetsLibrary.h>.
  • Change "My Photo Album" to the correct album name, and possibly set that statically
Fennelouski
  • 2,411
  • 1
  • 18
  • 26
  • The problem is easily solved using Photo Kit; using Assets Library is just a crutch. – matt Oct 13 '15 at 21:04
  • Great! I just added If statement, to create folder, if user deletes it. Thanks! – MOzeb Oct 13 '15 at 21:14
  • I don't disagree that it's not ideal, and there probably is a better option that is more iOS 9 appropriate, but this does work and fits the requirements for iOS 8. – Fennelouski Oct 13 '15 at 21:15