Search code examples
iosswiftcameraphotos

Error when trying to save a captured image in swift


In my project, I am capturing an image. But when it starts saving the image, app crashes with the error of -

"unexpectedly found nil while unwrapping"

My code is as follows-

//  Library Assets
    var assetCollection: PHAssetCollection!
    var photoAsset: PHFetchResult!

    let saveImage = UIImage(CGImage: cgImage, scale: 1, orientation: UIImageOrientation.Down)

                if let actualSaveImage = saveImage {
                //  Save image
                PHPhotoLibrary.sharedPhotoLibrary().performChanges({

                    let request = PHAssetChangeRequest.creationRequestForAssetFromImage(actualSaveImage)
                    let assetPlaceholder = request.placeholderForCreatedAsset
                    let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photoAsset)
                    albumChangeRequest.addAssets([assetPlaceholder])
                    self.buttonCapture.hidden = false
                    self.activityIndicator.stopAnimating()
                    self.lastShotFlag = false
                    }, completionHandler: {(success, error)in
                        NSLog("\nSave Image -> %@", (success ? "Success" : "Error!"))
                })
                }
                else {
                    NSLog("\nProblem in saveImage. It's nil.")
                }

After debugging it looks like I am not getting any value for the constant albumChangeRequest


Solution

  • The problem is that you have never given self.assetCollection or self.photoAsset any value, so they are nil. Thus, when you try to use them in your PHAssetCollectionChangeRequest initializer, you crash.

    By the way, if all you want to do is save the image into the camera roll, you don't need all that code. The creation request alone is all you need.

    Or, if you want to save the image into the camera roll and into an album, you don't need to call PHAssetCollectionChangeRequest(forAssetCollection:assets:) to do it.

    Finally, you really shouldn't have all that extra stuff in the change block. Just do the change and no more. The other stuff should be in the completion block.