如何访问仅在Swift中(如iOS中的图库)从相机拍摄的图像?

时间:2019-06-24 10:17:32

标签: ios swift uiimagepickercontroller phasset

在Android中,我们仅获得相机图像,即以编程方式打开图库时,而在iOS中,当我们打开照片时,我们获得相机胶卷图像和其他不需要的图像,如whatsapp图像。打开图库时如何仅过滤摄像机图像?

我在Swift 4中尝试过的内容如下所示:

func getPhotosAndVideos()
{
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]

    fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)

    print("fetchOptions : ", fetchOptions)

    let assets = PHAsset.fetchAssets(with: fetchOptions)

    var results = NSMutableArray()
    assets.enumerateObjects { (obj, idx, bool) -> Void in

        results.add(obj)
    }

    let cameraRollAssets = results.filtered(using: NSPredicate(format: "sourceType == %@", argumentArray: [3]))
    results = NSMutableArray(array: cameraRollAssets)

    print("cameraRollAssets : ", cameraRollAssets)

    print("results : ", results)
}

我只想用手机拍摄的相机图像。

1 个答案:

答案 0 :(得分:0)

嘿,您可以使用苹果的默认UIImagePickerController()来做到这一点

class testViewController: UIViewController {
    let picker = UIImagePickerController()
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBAction openPicker(_ sender: UIButton) {
      self.picker.sourceType = .savedPhotosAlbum
      self.picker.delegate = self
      self.present(self.picker, animated: true, completion: nil)
    }
}

extension testViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        print(info)
    }
}