With Swift 4 / iOS 10.3, you can choose one of the following methods to solve your problem.
1. Take a screenshot of the view controller view
The following code shows how to take a screenshot and save it in the deviceβs photo album:
import UIKit class ViewController: UIViewController { /* ... */ @IBAction func screenshot(_ sender: UIBarButtonItem) { //Create the UIImage UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0) guard let context = UIGraphicsGetCurrentContext() else { return } view.layer.render(in: context) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } }
Please note that the result of this code will be a .JPG image. Also note that the navigation bar and status bar will not be displayed in the final image.
Since iOS 10, as an alternative to the previous code, you can use the following code:
import UIKit class ViewController: UIViewController { @IBAction func screenshot(_ sender: UIBarButtonItem) {
2. Take a screenshot of the iPhone window
If you want to take a screenshot that includes a navigation bar (but not a status bar), you can use the following code:
import UIKit class ViewController: UIViewController { /* ... */ @IBAction func screenshot(_ sender: UIBarButtonItem) { //Create the UIImage guard let layer = UIApplication.shared.keyWindow?.layer else { return } UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0) guard let context = UIGraphicsGetCurrentContext() else { return } layer.render(in: context) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } }
Since iOS 10, as an alternative to the previous code, you can use the following code:
import UIKit class ViewController: UIViewController { @IBAction func screenshot(_ sender: UIBarButtonItem) {
Reminder
Starting with iOS 10, to prevent the crash of your application when calling the screenshot(_:) method, you need to add the NSPhotoLibraryUsageDescription key to the Info.plist project file:
<key>NSPhotoLibraryUsageDescription</key> <string>Some description to explain why access is required</string>