Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load animated GIF from photo library

In iOS Swift I'm having difficulty loading an animated GIF from the device photo library to a UIImageView or creating a .gif file from it. I have no problem displaying the animated GIF if it's a file on a server or if it's right in the app. However, when I load it from the photo library, I lose the animation. I found some Objective-C solutions and tried to convert them over to Swift, but haven't had any luck.

Here is what I have so far:

@IBAction func buttonTapped(sender: UIButton) {
    selectPhoto()
}

func selectPhoto() {
    let photoLibraryController = UIImagePickerController()
    photoLibraryController.delegate = self
    photoLibraryController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

    let mediaTypes:[String] = [kUTTypeImage as String]
    photoLibraryController.mediaTypes = mediaTypes
    photoLibraryController.allowsEditing = false

    self.presentViewController(photoLibraryController, animated: true, completion: nil)
}

// UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let origImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    self.imageView.image = origImage

    picker.dismissViewControllerAnimated(true, completion: nil)

}

Optimally, I would like to save the photo library image to a gif file on the server. From there I have no trouble displaying it. However, I need some help getting the data from the photo library into some type of property, without losing the animation. Do I need to use something like ALAssetsLibrary for this?

Thanks.

like image 697
Lastmboy Avatar asked Jun 21 '16 02:06

Lastmboy


1 Answers

Yes, Use ALAssetsLibrary → now called PHAsset.

You should get the NSData of the gif, not UIImage( because UIImage will only get the first frame.)

So basically you would do something like this:

One you get the asset

let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true // adjust the parameters as you wish    

PHImageManager.default().requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, UTI, _, _) in
    if let uti = UTI,let data = imageData ,
        // you can also use UTI to make sure it's a gif
       UTTypeConformsTo(uti as CFString, kUTTypeGIF) {
        // save data here
    }
})      

Resource: PHAsset

like image 90
XueYu Avatar answered Sep 19 '22 14:09

XueYu