【问题标题】:How to add latest photo of photo library to uiimageview using Swift?如何使用 Swift 将照片库的最新照片添加到 uiimageview?
【发布时间】:2016-11-28 10:08:00
【问题描述】:

有没有办法将我的照片库的最新照片添加到 uiimageview?我几乎尝试了所有方法,但没有任何效果。

【问题讨论】:

    标签: ios swift uiimageview gallery


    【解决方案1】:

    斯威夫特 3

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [SortDescriptor(key: "creationDate", ascending: true)]
    
    let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
    
    let last = fetchResult.lastObject
    
    if let lastAsset = last {
      let options = PHImageRequestOptions()
      options.version = .current
    
      PHImageManager.default().requestImage(
        for: lastAsset,
        targetSize: imageView.bounds.size,
        contentMode: .aspectFit,
        options: options,
        resultHandler: { image, _ in
          DispatchQueue.main.async {
            self.imageView.image = image
          }
        }
      )
    }
    

    斯威夫特 2

    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    
        let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
    
        let last = fetchResult.lastObject
    
        if let lastAsset = last {
            let options = PHImageRequestOptions()
            options.version = .Current
            options.deliveryMode = .HighQualityFormat
    
            PHImageManager.defaultManager().requestImageForAsset(
                lastAsset as! PHAsset,
                targetSize: imageView.bounds.size,
                contentMode: .AspectFit,
                options: options,
                resultHandler: { image, _ in
                    dispatch_async(dispatch_get_main_queue(), {
                        self.imageView.image = image
                    })
                }
            )
        }
    }
    

    【讨论】:

    • 代码在 Swift 2 中会是什么样子?抱歉,我之前从未使用过 Swift
    • 我会在一分钟内添加 Swift 2 版本。
    • 我已经添加了 Swift 2 版本。
    • 你还知道如何在 UIView 中显示视频吗?因为我想要一个照片库之类的东西,我可以在 UIView 中显示最新的视频和照片
    • 您需要MPMoviePlayerController
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 2011-07-07
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多