本篇又名:UIImagePickerController與GIF的形同陌路😂😂😂
結論就是,要選擇GIF要用新的PHPickerViewController
(iOS14以上),或是其他第三方套件,UIImagePickerController
會把它變成靜態截圖🤨
先準備一張可愛鴨鴨.gif
準備一個ViewController,裡面有一個ImageView用來顯示圖片+一個Label顯示圖片的副檔名+一個按鈕開UIImagePickerController
UIImagePickerController的Delegate
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true)
if let url = info[UIImagePickerController.InfoKey.imageURL] as? URL {
if let fileExtension = url.lastPathComponent.components(separatedBy: ".").last {
descLabel.text = "fileExtension: \(fileExtension)"
}
do {
let data = try Data(contentsOf: url)
imageView.image = UIImage(data: data)
} catch {
print(error.localizedDescription)
}
}
}
顯示選到一張jpeg檔
原因是UIImagePickerController
在 didFinishPickingMediaWithInfo
方法中,InfoKey.originalImage
返回的是被選取的照片的 UIImage。如果你選擇的是一個 GIF 檔案,originalImage
將是 GIF 的一張靜態快照而不是原始的 GIF 動畫。
另外CHATGPT説如果你想要取得原始的 GIF 檔案的 URL,你可以使用 InfoKey.imageURL
。
我用了還是給我截圖的jpeg
file:///private/var/mobile/Containers/Data/Application/BA887D86-726D-4D11-94BB-7DC0CB58F174/tmp/167A39CB-D85B-4F51-BDF2-2F2ABFBA4CFD.jpeg
如果要保留完整的GIF檔案,請用新出的PHPickerViewController
開啟PHPickerViewController
@IBAction func openImagePicker(_ sender: UIButton) {
var configuration = PHPickerConfiguration()
configuration.filter = .images //只能選圖片
configuration.selectionLimit = 1 // 一次只選一張
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = self
present(picker, animated: true)
}
選完圖片的Delegate
extension ViewController: PHPickerViewControllerDelegate {
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
let result = results.first
guard let selectedResult = results.first else { return }
selectedResult.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { (url, error) in
if let error = error {
print("Error loading file representation: \(error.localizedDescription)")
return
}
if let fileURL = url {
// 取得檔案副檔名
let fileExtension = fileURL.pathExtension
print("File Extension: \(fileExtension)")
do {
let data = try Data(contentsOf: fileURL)
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data)
self.descLabel.text = "File Extension: \(fileExtension)"
}
} catch {
print(error.localizedDescription)
}
}
}
}
}
上面用PHPickerViewController選到的副檔名是對的,但爲什麼圖片都不會動??
因為UIImage也不支援直接播放GIF動圖XDDDDDD需要另外處理
原生不同方法處理可看大大教學
因為我們已經是iOS13以上了,就用一個最簡單的方法來做
把放圖片那段改成播放GIF動畫
DispatchQueue.main.async {
let cfData = data as CFData
CGAnimateImageDataWithBlock(cfData, nil) { (_, cgImage, _) in
self.imageView.image = UIImage(cgImage: cgImage)
}
self.descLabel.text = "File Extension: \(fileExtension)"
}
動起來。:.゚ヽ(*´∀`)ノ゚.:。