Search code examples
iosobjective-cscreenshot

Screenshot doesn't appear at Photos app (iOS obj-c)


I'm trying to save screenshot of my app using next code:

UIView* view = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);

NSURL* documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSString* filename = [NSString stringWithUTF8String: @"screenshot.png"];
NSString* path =[NSString stringWithFormat:@"%@/%@",[documentsDirectory path], filename];

BOOL saved = [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
NSLog(saved ? @"Saved" : @"Not saved");

It logs Saved, but image doesn't appear in Photos app.

documentsDirectory: /var/mobile/Containers/Data/Application/003D7989-D88E-48FF-A3C5-86A340C6F077/Documents

What I'm doing wrong? Thanks for response.


Solution

  • try this code to save an Image in Photo app

    NSData * data = UIImagePNGRepresentation(image);
    UIImageWriteToSavedPhotosAlbum(compressedPNGImage,
                                   self,
                                   @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:),
                                   NULL);
    

    then you should implement the above selector as below

    - (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void*)ctxInfo
    {
        if (error)
        {
            // not saved
        }
        else
        {
            // saved
        }
    }
    

    finally, be sure to add "Privacy - Photo Library Usage Description" key in Info target settings