Search code examples
iossaveswift4arkitphoto-gallery

save arkit snapshot directly to photo gallery swift 4


The part of my code below takes a snapshot of the arkit and places it on a image view. I am trying to cut that out and and go from taking a photo and automatically saving it to the photo gallery without the need for placing it on a image view first.

    @IBOutlet var cryMeARiver: UIImageView!
@IBOutlet weak var augmentedRealityView: ARSCNView!

 @IBAction func place(_ sender: Any) {
//THIS LINE OF THE CODE BELOW SAVES THE SNAPSHOT TO THE IMAGEVIEW
cryMeARiver.image = augmentedRealityView.snapshot()
}

Solution

  • Since the snapshot function returns a UIImage it is very easy to save it to the IOS Photo Library.

    Before you begin, you need to ensure that in your info.plist you have set the following key:

      <key>NSPhotoLibraryUsageDescription</key>
      <string>To Save Your ARKit Scenes</string>
    

    Then you can call your function like so:

     @IBAction func saveScreenhot(){
    
            //1. Create A Snapshot
            let snapShot = self.augmentedRealityView.snapshot()
    
            //2. Save It The Photos Album
            UIImageWriteToSavedPhotosAlbum(snapShot, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    
     }
    

    Remembering of course to use the callback method to check whether the process was successful or not:

    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    
        if let error = error {
            print("Error Saving ARKit Scene \(error)")
        } else {
            print("ARKit Scene Successfully Saved")
        }
    }
    

    Hope it helps...