简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM