iOS Swift 4:获取图像格式(JPG,PNG,GIF)来自didFinishPickingMediaWithInfo

时间:2017-12-26 18:06:30

标签: ios swift swift4

我正在构建一个应用程序,允许您将库中的图像上传到服务器。该服务器本质上用作图像存储库。出于这个原因,绝对有必要将其存储在原始图像格式中:JPG,PNG或GIF。 I.E.如果PNG图像具有透明度,则要保留该图像,则不能简单地将其转换为JPG。

我使用UIImagePickerControllerReferenceURL来获取图像格式:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage
        let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL

        if (assetPath.absoluteString?.hasSuffix("JPG"))! {
            print("JPG")
        }
        else if (assetPath.absoluteString?.hasSuffix("PNG"))! {
            print("PNG")
        }
        else if (assetPath.absoluteString?.hasSuffix("GIF"))! {
            print("GIF")
        }
        else {
            print("Unknown")
        }

        self.dismiss(animated: true, completion: nil)

        self.showImageFieldModal(selectedImage: selectedImage)
    }

但iOS11中已弃用UIImagePickerControllerReferenceURL。它建议使用UIImagePickerControllerPHAsset,但这不是URL。我不确定我作为PHAsset对象应该做些什么...

1 个答案:

答案 0 :(得分:5)

在iOS11中,您可以使用原始图片网址密钥UIImagePickerControllerImageURL并使用网址resourceValues方法获取其typeIdentifierKey

if #available(iOS 11.0, *) {
    if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
        print(imageURL.typeIdentifier ?? "unknown UTI")  // this will print public.jpeg or another file UTI
    }
} else {
        // Fallback on earlier versions
}

您可以使用此answer中的typeIdentifier扩展名来查找fileURL类型标识符:

extension URL {
    var typeIdentifier: String? {
        return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
    }
}