2017-07-18 52 views
0

我嘗試使用下面的代碼保存我的應用程序的截圖:截圖不會出現在照片應用(iOS OBJ-C)

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

我做錯了什麼?感謝您的迴應。

回答

2

試試這個代碼保存圖像在照片應用

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 
    } 
} 

執行上述選擇最後,一定要加「隱私 - 圖片庫使用情況說明「鍵信息目標設置

+0

嗯,它現在保存到照片,但它是純白色圖像 –

+0

好吧,也許」圖像「是白色的:)我會更新源代碼;) – ddb

+0

我認爲你應該簡單地獲取當前viewController的視圖,而不是「UIView * view = [[[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];」 – ddb