最近写了个饭否客户端,传图片不支持gif,查了一圈终于弄好了,记录一下。主要问题在于取出来的gif默认只有第一帧,所以要用PHAsset处理下,获取一下mimeType, gif我转成了Data存起来了,png或者jpg就直接取图片然后压缩,再转成Data,然后用alamofire上传,也可以根据Data数据检测mimeType,我这里简单处理了一下mimeType,如果服务端要求可能要处理下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {


let mediaType = info[UIImagePickerController.InfoKey.mediaType] as! CFString
let assetPath = info[UIImagePickerController.InfoKey.referenceURL] as! URL

switch mediaType {
case kUTTypeImage, kUTTypeGIF:
if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
let options = PHImageRequestOptions()
options.isSynchronous = true
options.isNetworkAccessAllowed = false
options.deliveryMode = .fastFormat

guard let asset = PHAsset.fetchAssets(withALAssetURLs: [assetPath], options: nil).lastObject else { return }
PHImageManager.default().requestImageData(for: asset, options: options) { data, uti, orientation, info in
guard let info = info else { return }

if let error = info[PHImageErrorKey] as? Error {
debugPrint("Cannot fetch data for GIF image: \(error)")
return
}

if let isInCould = info[PHImageResultIsInCloudKey] as? Bool, isInCould {
debugPrint("Cannot fetch data from cloud. Option for network access not set.")
return
}


if uti == (kUTTypeGIF as String){
debugPrint(uti)
if let gifImageData = data {
self.imageData = gifImageData
self.mimeType = "image/gif"
}
} else {
let compressedImage = selectedImage.wxCompress()
self.imageData = compressedImage.jpegData(compressionQuality: 0.7)
self.mimeType = "image/png"
debugPrint("normal image")
}
}
}
case kUTTypeMovie:
if let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
// using video type
}
default:
debugPrint("Others")
}

let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
self.imageView.image = image

self.view.layoutIfNeeded()
picker.dismiss(animated: true, completion: nil)
}