iosswiftswift3photos

Swift: Load Photos images into app


I have an app which shows a screensaver when it detects that there is no user action. Currently, it is working as the images for the screensaver are preloaded into the app.

But ultimately I want the screensaver to access and show the images inside Photos as we would save promotion images into Photos and these images are subjected to frequent changes.

I am stuck and do not know how to proceed to access and read images from Photos.

Please help. :(

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)
    }

}

Solution

  • You can directly use Photos framework. I encourage you to read documentation first: https://developer.apple.com/documentation/photos

    Anyway, to get images, you can do it like this:

    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() 
    }
    

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