Swift Photo Library Access

时间:2017-05-12 17:43:09

标签: ios swift swift3 photo

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

谢谢!

1 个答案:

答案 0 :(得分:9)

这不是那么简单,但正如Rob所提到的,你可以保存照片资产网址,然后使用照片框架获取它。您可以使用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并添加"隐私 - 照片库使用说明"

Sample