Swift照片库访问?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (35)

我想从我的应用中的用户照片库中访问照片,并且正在查看UIImagePickerController。但是,我想知道是否可以访问和查看照片库中的照片,而无需将这些照片实际存储在应用程序中?所以基本上应用程序会存储对所选照片的​​引用,而不是自己存储照片。这是为了防止应用程序占用大量的空间来存储每张照片。

提问于
用户回答回答于

你可以保存照片素材资源网址,然后使用Photos框架获取它。你可以使用PHImageManager方法requestImageData获取它们。

import UIKit
import Photos
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    @IBOutlet weak var imageView: UIImageView!
    let galleryPicker = UIImagePickerController()
    // create a method to fetch your photo asset and return an UIImage on completion
    func fetchImage(asset: PHAsset, completion: @escaping  (UIImage) -> ()) {
        let options = PHImageRequestOptions()
        options.version = .original
        PHImageManager.default().requestImageData(for: asset, options: options) {
            data, uti, orientation, info in
            guard let data = data, let image = UIImage(data: data) else { return }
            self.imageView.contentMode = .scaleAspectFit
            self.imageView.image = image
            print("image size:", image.size)
            completion(image)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // lets add a selector to when the user taps the image
        let tap = UITapGestureRecognizer(target: self, action: #selector(openPicker))
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
    // opens the image picker for photo library
    func openPicker() {
        galleryPicker.sourceType = .photoLibrary
        galleryPicker.delegate = self
        present(galleryPicker, animated: true)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // check if there is an url saved in the user defaults
        // and fetch its first object (PHAsset)
        if let url = UserDefaults.standard.url(forKey: "assetURL"),
            let asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil).firstObject {
            fetchImage(asset: asset) { self.imageView.image = $0 }
        }

    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true)
        print("canceled")
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let url = info[UIImagePickerControllerReferenceURL] as? URL,
            let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            UserDefaults.standard.set(url, forKey: "assetURL")
            print("url saved")
            self.imageView.image = image
        }
        dismiss(animated: true)
    }
}

注意:不要忘记编辑你的信息plist,并添加“隐私 - 图片库使用说明”

扫码关注云+社区

领取腾讯云代金券