How to save GIFs with the PHPhotoLibrary?

吃可爱长大的小学妹 提交于 2019-12-10 15:57:03

问题


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")
    }
  }
}

来源:https://stackoverflow.com/questions/40370773/how-to-save-gifs-with-the-phphotolibrary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!