使用Swift 3

时间:2017-06-22 02:54:13

标签: ios arrays swift

我正在编写一个具有屏幕保护程序的应用程序,该屏幕保护程序遍历iPad的相机胶卷中的照片。我坚持要将图像文件名存储到一个数组中,以便我可以相应地显示图像。

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

1 个答案:

答案 0 :(得分:1)

我收到了你的问题。现在创建函数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)
}

比用你的功能调用它

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

注意:在调用FetchPhotos()func到viewDidLoad时要小心,因为func convertAssetToImage是异步函数。