Andrew Harris
Andrew Harris

Reputation: 416

Why does the screenshot show just white when I'm trying to take a screenshot of my app programmatically in Swift?

On my app, I have a view which holds a camera. I want to take a screenshot of this view which holds the camera. However when I do this with the following code:

let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

the screenshot which was saved to photos is just blank and doesn't show the camera view.

Upvotes: 1

Views: 2977

Answers (1)

djromero
djromero

Reputation: 19641

Render and capture an UIView named view:

UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
view.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();

Remember that UIWindow is a view too. You can test in the simulator saving to the desktop with this function:

public func saveImageToDesktop(image : UIImage, name : String)
{
    let basePath = NSString(string: "~/Desktop").stringByExpandingTildeInPath
    let path = "\(basePath)/\(name).png"
    UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
}

Upvotes: 3

Related Questions