功能需求:使用UIImagePickerController选择图片,然后上传。
环境:iPhoneSE,iOS 11.1.2(15B202),手机的照片启用了iCloud照片图库,选中了优化iPhone存储空间,如下图
代码:
let imgPVc = UIImagePickerController()
func showPhotoContrller(library:Bool) {
self.imgPVc.delegate = self
self.imgPVc.allowsEditing = true
self.imgPVc.mediaTypes = [kUTTypeImage as String]
self.imgPVc.modalPresentationStyle = .fullScreen
if library {
self.imgPVc.sourceType = .photoLibrary
}
else {
self.imgPVc.sourceType = .camera
}
if #available(iOS 11.0, *) {
self.imgPVc.imageExportPreset = .current
}
self.viewController?.present(self.imgPVc, animated: true, completion: nil)
}
回调
extension CHPhotoNative: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
qlog(message: "pick photo finish \n\(info)")
self.imgPVc.dismiss(animated: true, completion: nil)
let tmpUserHeader = NSTemporaryDirectory().appending("/tmpuserheader.jpg")
if let img = info[UIImagePickerControllerEditedImage] as? UIImage {
if let imgData = imgDataFromUIImage(img: img) as NSData? {
try? imgData.write(toFile: tmpUserHeader, options: .atomicWrite)
self.callJs(jsFuncName: callback, data: tmpUserHeader)
return
}
}
self.callJs(jsFuncName: callback, data: nil)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
qlog(message: "pick photo cancel")
self.callJs(jsFuncName: self.callback, data: nil)
self.imgPVc.dismiss(animated: true, completion: nil)
}
}
异常:选中照片的时候会从iCloud下载照片,然后进入编辑界面,在编辑界面点击“选取”,控制台就打印错误信息,并且app的界面不能再操作。打印信息如下,回调没有执行,程序没有crash,但是界面不可再操作。
2018-12-05 15:30:54.988544+0800 EuropeAIHome[33081:16424558] [general] <NSXPCConnection: 0x1c030d6e0> connection from pid 33097: Warning: Exception caught during invocation of received message, dropping incoming message and invalidating the connection.
Exception: *** -[NSURL URLByAppendingPathExtension:]: component, components, or pathExtension cannot be nil.
*** -[NSURL URLByAppendingPathExtension:]: component, components, or pathExtension cannot be nil.
(
0 CoreFoundation 0x0000000185371d1c <redacted> + 148
1 libobjc.A.dylib 0x00000001845c0528 objc_exception_throw + 56
2 CoreFoundation 0x0000000185371c4c <redacted> + 0
3 Foundation 0x0000000185d8491c <redacted> + 92
4 PhotosUI 0x0000000198287928 <redacted> + 1660
5 PhotosUI 0x0000000198286db4 <redacted> + 36
6 Foundation 0x0000000185e871e0 <redacted> + 20
7 Foundation 0x0000000185e8597c <redacted> + 2632
8 Foundation 0x0000000185c5c830 <redacted> + 240
9 libxpc.dylib 0x0000000184fd67d0 <redacted> + 68
10 libxpc.dylib 0x0000000184fd4168 <redacted> + 984
11 libdispatch.dylib 0x0000000104d0552c _dispatch_client_callout4 + 16
12 libdispatch.dylib 0x0000000104d08f58 _dispatch_mach_msg_invoke + 380
13 libdispatch.dylib 0x0000000104d13f30 _dispatch_queue_serial_drain + 212
14 libdispatch.dylib 0x0000000104d084c0 _dispatch_mach_invoke + 992
15 libdispatch.dylib 0x0000000104d13f30 _dispatch_queue_serial_drain + 212
16 libdispatch.dylib 0x0000000104d089a4 _dispatch_queue_invoke + 332
17 libdispatch.dylib 0x0000000104d15104 _dispatch_root_queue_drain_deferred_wlh + 424
18 libdispatch.dylib 0x0000000104d1c100 _dispatch_workloop_worker_thread + 652
19 libsystem_pthread.dylib 0x0000000184f9afd0 _pthread_wqthread + 932
20 libsystem_pthread.dylib 0x0000000184f9ac20 start_wqthread + 4
)
根据打印信息可以得知,之所以报错,是因为NSURL的URLByAppendingPathExtension方法的参数为nil导致的,但是这个界面是苹果的,我们没有办法修改,怎么办呢;
鄙人的解决方法是,使用runtime机制,替换NSURL的URLByAppendingPathExtension方法,在新方法中判断参数是否为nil,代码如下(代码基于swift4,OC的话,就可以用load方法替换initializeMethod方法,详情请搜索iOS Swizzling)
extension NSURL {
public class func initializeMethod() {
DispatchQueue.once(token: "NSURL.initializeMethod") {
if let m1 = class_getInstanceMethod(self, #selector(NSURL.appendingPathExtension)) {
method_exchangeImplementations(m1, class_getInstanceMethod(self, #selector(ex_URLByAppendingPathExtension(component:)))!);
}
}
}
@objc func ex_URLByAppendingPathExtension(component:String?) {
if let com = component {
self.ex_URLByAppendingPathExtension(component: com)
}
}
}
swift 没有DispatchQueue.once方法,添加一个extension来实现该功能。
extension DispatchQueue {
private static var onceTracker = [String]()
open class func once(token: String, block:() -> Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if onceTracker.contains(token) {
return
}
onceTracker.append(token)
block()
}
}
这样子之后,就可以看到,当选中图片之后,ex_URLByAppendingPathExtension方法的参数确实为nil,这样处理之后,app就可以继续运行,但是可能会有新的打印信息。
2018-12-05 15:58:05.871301+0800 EuropeAIHome[33216:16440651] [Generic] -[PUPhotoPickerExtensionHostContext _UIImagePickerControllerInfoDictionaryFromPhotoPickerInfoDictionary:] Unable to copy from file:///var/mobile/Media/PhotoData/CPLAssets/group173/DFA0B171-1286-428F-95D8-692ACC515759.JPG to file:///private/var/mobile/Containers/Data/Application/3ABF885C-332D-45BC-B151-1ACA6D8D0538/tmp/9C8CD5C9-74B7-4EE7-99A3-F02EDDFC55F2 Error Domain=NSCocoaErrorDomain Code=260 "未能打开文件“DFA0B171-1286-428F-95D8-692ACC515759.JPG”,因为它不存在。" UserInfo={NSFilePath=/var/mobile/Media/PhotoData/CPLAssets/group173/DFA0B171-1286-428F-95D8-692ACC515759.JPG, NSUnderlyingError=0x1c564e160 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
2018-12-05 15:58:05.873+0800 CHPhotoNative.swift[imagePickerController(_:didFinishPickingMediaWithInfo:):89] pick photo finish
["UIImagePickerControllerCropRect": NSRect: {{0, 316}, {2303.9998901367239, 2305}}, "UIImagePickerControllerImageURL": file:///private/var/mobile/Containers/Data/Application/3ABF885C-332D-45BC-B151-1ACA6D8D0538/tmp/9C8CD5C9-74B7-4EE7-99A3-F02EDDFC55F2, "UIImagePickerControllerPHAsset": <PHAsset: 0x1511675d0> E07D54CC-593E-4CB3-9E13-357943927F56/L0/001 mediaType=1/0, sourceType=1, (3024x4032), creationDate=2018-07-01 03:38:21 +0000, location=1, hidden=0, favorite=0 , "UIImagePickerControllerEditedImage": <UIImage: 0x1c46b2720> size {638, 640} orientation 0 scale 1.000000, "UIImagePickerControllerMediaType": public.image, "UIImagePickerControllerReferenceURL": assets-library://asset/asset.JPG?id=E07D54CC-593E-4CB3-9E13-357943927F56&ext=JPG]
但是这个并不影响图片的使用,info的UIImagePickerControllerEditedImagekey的value然后可以获取到编辑后的图片,UIImagePickerControllerPHAsset的value也仍然有数据。