

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to take a screenshot programmatically in iPhone/iOS?
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.
- Related Questions & Answers
- How to programmatically take a screenshot on iOS?
- How to programmatically take a screenshot in android?
- How to take a screenshot programmatically in Android using Kotlin?
- How to take a screenshot of my iOS application in the iOS simulator?
- How to get the MAC address of an iOS/iPhone programmatically?
- How to take screenshot in Android Programatically?
- How to create a WebView in iOS/iPhone?
- How to take screenshot with Selenium WebDriver?
- How to take screenshot of a div with JavaScript
- How to compare two NSDates in iPhone/iOS?
- How to add 1 day to a Date in iOS/iPhone?
- How to take partial screenshot (frame) with Selenium WebDriver?
- How to access RESTFul services from iOS/iPhone?
- How to take a screenshot of the window using Python?(Tkinter)
- How to take partial screenshot with Selenium WebDriver in python?