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

时间:2018-01-18 09:09:31

标签: ios swift swift3 photos

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

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

我陷入困境,不知道如何继续访问和阅读照片中的图像。

请帮忙。 :(

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

}

2 个答案:

答案 0 :(得分:2)

您可以直接使用Photos框架。我建议您先阅读文档: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

答案 1 :(得分:0)

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

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