swift 4 如何从 UIImagepicker 中选取 GIF 图片?

How to pick GIF image from UIImagepicker in swift 4?

在我的项目中尝试从 UIImage 选择器导入 GIF。从图库中选取的 GIF 图像将执行某些操作,例如播放和停止。现在我可以从图库中 select GIF 法师,但结果显示为图像而不是 gif 图像。

谁能帮我解决这个问题。

试试这个对你有帮助。

第一步:创建全局变量

var IMG:String?

第 2 步:将此函数放入您的代码中。

    func getFileName(info: [String : Any]) -> String {

    if let assetPath = info[UIImagePickerControllerReferenceURL] as? URL {
        let result = PHAsset.fetchAssets(withALAssetURLs: [assetPath], options: nil)
        let asset = result.firstObject
        let fileName = asset?.value(forKey: "filename")
        let fileUrl = URL(string: fileName as! String)
        if let name = fileUrl?.deletingPathExtension().lastPathComponent {
            print(name)


   //let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
            if (assetPath.absoluteString.hasSuffix("JPG")) {
                sonu = "JPG"
                print("JPG")
            }
            else if (assetPath.absoluteString.hasSuffix("PNG")) {
                sonu = "PNG"
                print("PNG")
            }
            else if (assetPath.absoluteString.hasSuffix("GIF")) {
                sonu = "GIF"
                print("GIF")
            }
            else {
                sonu = "Unknown"
                print("Unknown")
            }

            return name
        }
    }
    return ""

}

第 3 步:在您的 ImagePickerController

中设置此代码
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage
    {
        imageview.image = image
        let IMG = getFileName(info: info)
        print(IMG)
        if IMG == "JPG"
        {
            imageDataForApi = UIImagePNGRepresentation(image)
        }
        else if IMG == "GIF"
        {
            imageDataForApi = UIImageJPEGRepresentation(image, 0)
        }
    }
    self.dismiss(animated: true) { () -> Void in

    }