How to download animated GIF from photo library

In iOS Swift, it’s hard for me to upload an animated GIF from the device’s photo library to UIImageView or create a .gif file from it. I have no problem displaying an animated GIF if it is a file on the server or it is right in the application. However, when I download it from the photo library, I lose the animation. I found several Objective-C solutions and tried to convert them to Swift, but with no luck.

Here is what I still have:

@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 image of the photo library to a gif file on the server. From there I see nothing. However, I need help getting the data from the photo library to some type of property, without losing the animation. Should I use something like ALAssetsLibrary for this?

Thanks.

+4
ios swift gif uiimagepickercontroller animated-gif
source share
1 answer

Yes, use ALAssetsLibrary -> now called PHAsset.

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

So basically you would do something like this:

You get an 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 a gif UTTypeConformsTo(uti as CFString, kUTTypeGIF) { // save data here } }) 

Resource: PHAsset

+6
source share

All Articles