How to take a screenshot programmatically in iPhone/iOS?

iOSMobile DevelopmentiPhone/iPad

Though iOS does not provide any official way to take screenshots on iOS device programmatically, it provides a way to screenshot using the home and power button, by pressing both of them at the same time.

To take a screenshot, we’ll have to go through a series of steps.

  • We’ll get the layer of keyWindow – UIApplication.shared.keyWindow!.layer

  • We’ll get the scale of screen – UIApplication.main.scale

  • Creating a new image with same size as the view.

  • Render and save the image.

Let’s create a new project, in the main view controller give some background color and then drag a button and connect to create an action to its class. Add the following code in the action.

@IBAction func takeshot(_ sender: Any) {
   var image :UIImage?
   let currentLayer = UIApplication.shared.keyWindow!.layer
   let currentScale = UIScreen.main.scale
   UIGraphicsBeginImageContextWithOptions(currentLayer.frame.size, false, currentScale);
   guard let currentContext = UIGraphicsGetCurrentContext() else {return}
   currentLayer.render(in: currentContext)
   image = UIGraphicsGetImageFromCurrentImageContext()
   UIGraphicsEndImageContext()
   guard let img = image else { return }
   UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil)
}

While using this for the first time you’ll have to allow photos permission to save the image. The saved image will be in .jpg format.

Also add a “NSPhotoLibraryAddUsageDescription” to the info.plist of your app.

This can be converted to a function and used at multiple places, or as an extension.

This is how the app looks. When you run it.

After running for very first time and clicking on the take shot button

After you allow access, go to the photos app on you iPhone and the picture will be found there. 

raja
Published on 28-Dec-2018 16:15:46
Advertisements