ios - 如何像 iOS 中的图库一样仅在 Swift 中访问从相机拍摄的图像?

标签 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)
}

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

最佳答案

嘿,你可以使用苹果默认的 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)
    }
}

关于ios - 如何像 iOS 中的图库一样仅在 Swift 中访问从相机拍摄的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56734440/

相关文章:

ios - 如何在 Storyboard 应用程序中共享一个 UIView

ios - 如何在 1 天后快速重置特定变量值

ios - 如何将 iPhone 库中的视频导入我的应用程序?

iOS 9 UIImagePickerController statusBar 白色

android - 是否有适用于 Android 和 iOS 的 OCR 开源库或 sdk(免费)?

ios - Swift NSCalendar.currentCalendar().isDateInToday.() 无法正常工作

iphone - 游戏中3D模型动画的基本解释

swift - 如何制作一个可重用的 SwiftUI View ,其主体可以像列表一样填充?

ios - 将 ViewController 的 View 分配给自定义 View 类不会显示自定义 View 属性

ios - 为什么 UIImagePickerController 不委托(delegate)给我的 Object 类?