PHAsset:拍照完获取PHAsset对象

发布朋友圈项目遇到:拍照完需获取PHAsset对象

解决方案:

将拍下的相片保存到相册,再从相册读取PHAsset

swift代码:

import UIKit
import Photos

class cameraPicker: NSObject, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    static let `default` = cameraPicker()
    //选择完成调用block
    var cameraPickerFinish:((_ imageAsset: PHAsset)->())?
    
    override init() {
    }
    
    //拍照
    func show(parentVC: UIViewController) {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .camera
        imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
        parentVC.present(imagePicker, animated: true, completion: nil)
    }
    
    //选择完成
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            //此处先保存至相册
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
    }
    
    //从相册读取
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        //获取相册最新的一张
        let option = PHFetchOptions()
        //ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列
        option.sortDescriptors =  [NSSortDescriptor(key: "creationDate", ascending: false)]
        let result = PHAsset.fetchAssets(with: .image, options: option)
        let phasset = result.firstObject
        
        if let imageAsset = phasset {
            //选中的图
            if let block = self.cameraPickerFinish {
                block(imageAsset)
            }
        }
    }

}

PHAsset其他方法
PHAsset 转换为 image
            // 新建一个默认类型的图像管理器imageManager
            let imageOptions = PHImageRequestOptions()
            imageOptions.resizeMode = .exact
            // 缩略图的质量为高质量
            imageOptions.deliveryMode = .highQualityFormat

            PHImageManager.default().requestImage(for: imageAsset, targetSize: CGSize(width: SCREEN_WIDTH*2, height: SCREEN_HEIGHT*2), contentMode: PHImageContentMode.aspectFill, options: imageOptions, resultHandler: { (image, info) -> Void in
                    if image != nil {
                        //添加到数组
                        imageArray.append(image!)
                    }
            })

你可能感兴趣的:(PHAsset:拍照完获取PHAsset对象)