Search code examples
iosswiftnsdataalassetslibrary

How can I convert photo (or video) from camera to NSData?


In my app I take photo and then save url to it using ALAssetsLibrary. This code looks like this:

   ALAssetsLibrary().writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!,
                completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
                    if(error == nil){
                           path.save()
                           //.......
                    }
            })

I need to transform the photo that I took to NSData object. So how can I substitute this code according to IOS 9.0 guidelines (I know that ALAssetsLibrary is deprecated in IOS 9)? And how can I transform my photo to NSData object?


Solution

  • Since ALAssetsLibrary is deprecated, you should use the Photos library. See below code example.

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
    
        let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
    
        }, completionHandler: { (success, error) -> Void in
    
        if success {
            //image saved to photos library.
        }
    })
    

    If you need to transform the image to NSData, you could simply use (as pointed out by @if-else-switch )

    UIImagePNGRepresentation(image)
    

    Hope that helps!