我试图使用下一代码保存我应用的屏幕截图:
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");
它会记录Saved
,但图片不会显示在照片应用中。
documentsDirectory
:/var/mobile/Containers/Data/Application/003D7989-D88E-48FF-A3C5-86A340C6F077/Documents
我做错了什么?谢谢你的回复。
答案 0 :(得分:2)
尝试使用此代码在Photo app中保存图像
NSData * data = UIImagePNGRepresentation(image);
UIImageWriteToSavedPhotosAlbum(compressedPNGImage,
self,
@selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:),
NULL);
然后你应该实现上面的选择器
- (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void*)ctxInfo
{
if (error)
{
// not saved
}
else
{
// saved
}
}
最后,请务必在信息目标设置中添加“隐私 - 照片库使用说明”键