How to save GIFs with the PHPhotoLibrary?
Asked Answered
M

0

4

I have an app that displays GIFs from the internet and I am trying to add the ability to save a GIF to the camera roll. I am using the PHPhotoLibrary and I was trying to save it to the camera roll using the method I've seen in several SO questions such as this one:

func saveToCameraRoll(imageUrl: String) {
    PHPhotoLibrary.shared().performChanges({ _ in
      let createRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(
        atFileURL: URL(string: imageUrl)!)
    }) { success, error in
      guard success else {
        log.debug("failed to save gif \(error)")
        return
      }
      log.debug("successfully saved gif")
    }
  }

However this gives me failed to save gif Optional(Error Domain=NSCocoaErrorDomain Code=-1 "(null)"), which seems to be because of the .gif file format, but I cannot find another example of how to save to the camera roll without using the deprecated ALAssetsLibrary.writeImageDataToSavedPhotosAlbum.

I tried saving a GIF from Safari, and that worked: the GIF animated when sent to someone else, so I know what I'm trying to do is possible, but can someone point me towards the right part of the PHPhotoLibrary API?

EDIT: Based on this answer to a similar question, I figured out how to do what I wanted with Data and PHAssetCreationRequest as follows:

class func saveToCameraRoll(imageUrl: String) {
  ImageService.GetImageData(url: imageUrl) { data in // This helper function just fetches Data from the url using Alamofire
    guard let data = data else { return }
    PHPhotoLibrary.shared().performChanges({ _ in
      PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil)
    }) { success, error in
      guard success else {
        log.debug("failed to save gif \(error)")
        return
      }
      log.debug("successfully saved gif")
    }
  }
}
Morea answered 2/11, 2016 at 0:43 Comment(2)
Caveat emptor: GIFs aren't fully supported by Photos. As you've noticed, it'll preserve the file data that went into it, and regurgitate the same file data when you try to share it from the Photos app, but other devices on iCloud Photo Library might not see the original GIF in some circumstances, and the GIF animation won't be preserved when a user edits the asset in the Photos app.Bracey
@Bracey Yeah, I'm aware of that, I just wanted the user to be able to send my GIFs through Messages, and they do animate there, so that's all I care about. Holding out hope that one day Apple will actually support GIFs, but at this rate the web will finish switching to silent videos before that happens.Morea

© 2022 - 2024 — McMap. All rights reserved.