快速照片库访问 [英] Swift Photo Library Access

查看:19
本文介绍了快速照片库访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to access photos from the user's photo library in my app and I was looking at the UIImagePickerController to do so. However, I was wondering if it is possible to access and view the photos from the photo library without actually storing those photos in the app? So basically the app would store references to the selected photos, rather than storing the photos themselves. This is to prevent the app from taking up large amounts of space from storing each photo.

谢谢!

推荐答案

它不是那么简单,但正如 Rob 提到的,您可以保存照片资产 url,然后使用照片框架获取它.您可以使用 PHImageManager 方法 requestImageData 获取它们.

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
    override func viewDidLoad() {
        super.viewDidLoad()
        // lets add a selector to when the user taps the image
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openPicker)))
        // request authorization
        switch PHPhotoLibrary.authorizationStatus() {
        case .authorized:
            print("The user has explicitly granted your app access to the photo library.")
            return
        case .denied:
            print("The user has explicitly denied your app access to the photo library.")
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { status in
                print("status", status)
            }
        case .restricted:
            print("Your app is not authorized to access the photo library, and the user cannot grant such permission.")
        default: break
        }
    }
    // opens the image picker for photo library
    @objc func openPicker(_ gesture: UITapGestureRecognizer) {
        galleryPicker.sourceType = .photoLibrary
        galleryPicker.delegate = self
        present(galleryPicker, animated: true)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.imageView.contentMode = .scaleAspectFit
        // check if there is an url saved in the user defaults
        // and fetch its first object (PHAsset)
        if let assetURL = UserDefaults.standard.url(forKey: "assetURL") {
            if let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).firstObject {
                asset.asyncImageData { data, _, _, _ in
                    print("fetched")
                    guard let data = data else { return }
                    self.imageView.image = UIImage(data: data)
                }
            } else {
                print("assetURL:", assetURL)
                self.imageView.image = UIImage(contentsOfFile: assetURL.path)
            }
        } else {
            print("no assetURL found")
        }

    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true)
        print("canceled")
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        self.imageView.image = info[.originalImage] as? UIImage
        if let phAsset = info[.phAsset] as? PHAsset {
            phAsset.asyncURL { url in
                guard let url = url else { return }
                UserDefaults.standard.set(url, forKey: "assetURL")
                print("assetURL saved")
            }
        }
        dismiss(animated: true)
    }
}

<小时>

extension PHAsset {
    func asyncURL(_ completion: @escaping ((URL?) -> Void)) {
        switch mediaType {
        case .image:
            let options: PHContentEditingInputRequestOptions = .init()
            options.canHandleAdjustmentData = { _ in true }
            requestContentEditingInput(with: options) { editingInput, _ in
                completion(editingInput?.fullSizeImageURL)
            }
        case .video:
            let options: PHVideoRequestOptions = .init()
            options.version = .original
            PHImageManager.default()
                .requestAVAsset(forVideo: self, options: options) { asset, _, _ in
                completion((asset as? AVURLAsset)?.url)
            }
        default:
            completion(nil)
        }
    }
    func asyncImageData(version: PHImageRequestOptionsVersion = .original, completion: @escaping  (Data?, String?, UIImage.Orientation, [AnyHashable : Any]?) -> ()) {
        let options = PHImageRequestOptions()
        options.version = version
        PHImageManager.default()
            .requestImageData(for: self, options: options, resultHandler: completion)
    }
}
extension URL {
    var phAsset: PHAsset? {
        PHAsset.fetchAssets(withALAssetURLs: [self], options: nil).firstObject
    }
}

<小时>

注意:不要忘记编辑您的信息 plist 并添加隐私 - 照片库使用说明"


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

示例

这篇关于快速照片库访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆