Swift Photo Library Access

社会主义新天地 提交于 2019-11-28 12:51:10

It is not so simple but as mentioned by Rob you can save the photo asset url and later fetch it using the Photos framework. You can fetch them using PHImageManager method 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)
    }
}

Note: Don't forget to edit your info plist and add "Privacy - Photo Library Usage Description"

Sample

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!