UIImagePickerController和iCloud照片

时间:2014-07-29 10:02:26

标签: ios swift uiimagepickercontroller icloud

切换到iCloud Photo后,似乎UIImagePickerController返回的一些图像非常模糊。看起来图像来自iCloud Photo。

我能够检索原始图像,还是过滤掉iCloud Photo图像,还是必须切换到其他框架来执行UIImagePickerController的操作?

1 个答案:

答案 0 :(得分:3)

从症状来看,我假设您正在使用类似的方法来加载图像:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            loadImageInMemory(image)
        }
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

其中loadImageInMemory是处理图像的功能。

事实证明,如果使用该方法,则在iCloud上存储的图像的检索质量可能会低于原始图像。验证情况的一种方法是更改​​“照片”设置。在“设置”应用中:

Settings -> Photos -> Download and Keep Originals

这可以解决问题,但是当然不是可取的。如果您想继续使用照片,而不是实施自己的iCloud解决方案,而保留Optimize iPhone Storage设置,则可以使用PhotoKit来检索原始图像。

改为使用以下代码:

import Photos

// ...

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // it will be loaded asynchronously
        loadImageFromPicker(info: info)
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

    private func loadImageFromPicker(info: [UIImagePickerController.InfoKey : Any]) {
        var phAsset: PHAsset?
        if #available(iOS 11.0, *) {
            phAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset
        } else {
            // Fallback on earlier versions
            if let referenceURL = info[UIImagePickerController.InfoKey.referenceURL] as? URL {
                let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
                phAsset = fetchResult.firstObject
            }
        }
        guard let asset = phAsset else {
            return
        }
        // size doesn't matter, because resizeMode = .none
        let size = CGSize(width: 32, height: 32)
        let options = PHImageRequestOptions()
        options.version = .original
        options.deliveryMode = .highQualityFormat
        options.resizeMode = .none
        options.isNetworkAccessAllowed = true
        PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options) { [weak self] (image, info) in
            if let s = self, let image = image {
                s.loadImageInMemory(image)
            }
        }
    }

此代码将与本地图像和iCloud图像一起使用。

这解决了我使用alpha的小PNG图像时遇到的类似问题。请参阅this other post以供参考。