Swift:将照片图像加载到应用程序中

Swift: Load Photos images into app

我有一个应用程序,当它检测到没有用户操作时会显示屏幕保护程序。目前,它正在运行,因为屏幕保护程序的图像已预加载到应用程序中。

但最终我希望屏幕保护程序能够访问和显示照片中的图像,因为我们会将宣传图像保存到照片中,而这些图像会经常更改。

我卡住了,不知道如何继续访问和读取照片中的图像。

请帮忙。 :(

import UIKit
import Photos

class ScreenSaverViewController: UIViewController {
    @IBOutlet weak var ssImage: UIImageView!

    var timer = Timer()
    var count = 0

    var arrayPhoto: [UIImage] = [
        UIImage(named:"0.jpg")!,
        UIImage(named:"1.jpg")!,
        UIImage(named:"2.jpg")!,
        UIImage(named:"3.jpg")!
    ]

    var images = [PHAsset]()

    func nextImage() {
         let currentIndex = arrayPhoto.index(of: ssImage.image ?? UIImage()) ?? -1

         var nextIndex = currentIndex + 1

         nextIndex = arrayPhoto.indices.contains(nextIndex) ? nextIndex : 0

         UIView.transition(with: ssImage, duration: 0.5, options: .transitionCrossDissolve, animations: { self.ssImage.image = self.arrayPhoto[nextIndex] }, completion: nil)


    }

    func scheduledTimer(){
         timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: (#selector(nextImage)), userInfo: nil, repeats: true)
         count = 1
    }

    override func viewDidLoad() {
         super.viewDidLoad()
         if count == 0 {
              ssImage.image = UIImage(named: "0.jpg")
         }
         scheduledTimer()
    }

    override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         timer.invalidate()
         self.dismiss(animated: true, completed: nil)
    }

}

我认为您应该在您的应用中提供一个按钮,点击该按钮将打开 UIImagePickerController,来源类型为 .photos。该应用程序的用户可以 select 他希望屏幕保护程序中包含的图像。

实施协议 UIImagePickerControllerUINavigationControllerDelegate,特别是函数 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]),您可以在其中访问 selected 图像。然后,您可以将这些图像保存到应用程序的文档文件夹中,并在显示屏幕保护程序时使用它们。

您可以直接使用照片框架。我鼓励您先阅读文档:https://developer.apple.com/documentation/photos

无论如何,要获取图像,您可以这样做:

func getImages() {
    let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
    assets.enumerateObjects({ (object, count, stop) in
        self.images.append(object)
    })

    //In order to get latest image first, we just reverse the array
    images.reverse() 
}

致谢:Swift 3: Load photos from Photos/Camera Roll without using UIImagePickerController