Spiral1ng
Spiral1ng

Reputation: 323

Store image file names into array with Swift 3

I am writing an app that has a screensaver which traverses the photos from the Camera Roll of the iPad. I am stuck at getting the image file names to be stored into an array so that i can display the image accordingly.

import Photos

@IBOutlet weak var ssImage: UIImageView!
let fetchOptions = PHFetchOptions()
var arrayPhoto: [UIImage] = []

func FetchPhotos() {
    let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)

    //Get the file names of all the photos and store into arrayPhoto
}

//Gets index of current image from array and increment 1 so as to display the next photo every 5 seconds.
func nextImage() {
    let currentIndex = arrayPhoto.index(of: imageView.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)
    ssImage.image = arrayPhoto[nextIndex]
}

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

override func viewDidLoad() {
    super.viewDidLoad
    FetchPhotos()
    scheduledTimer()
}

Upvotes: 2

Views: 841

Answers (1)

Leang Socheat
Leang Socheat

Reputation: 1174

I got your question. now create function convertAssetToImage

func convertAssetToImage(asset: [PHAsset], completion: (_ objects: [UIImage]) -> Void) {
    var result: [UIImage] = []
    asset.forEach { (item) in

        imageManager.requestImage(for: item, targetSize: CGSize(width: item.pixelWidth, height: item.pixelHeight), contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
            // The cell may have been recycled by the time this handler gets called;
            // set the cell's thumbnail image only if it's still showing the same asset.
            result.append(image!)
        })

    }
    completion(result)
}

than call it with your function

func FetchPhotos() {
  let photoAssets = PHAsset.fetchAssets(with: .image, options: fetchOptions)
  convertAssetToImage(asset: photoAssets, completion: { (images) in
                        arrayPhoto = images
                    })
}

Note: be careful when call FetchPhotos() func to viewDidLoad because func convertAssetToImage is asynchronous func.

Upvotes: 1

Related Questions