尝试从DocumentDirectory路径获取图像时出错

时间:2016-09-05 17:54:36

标签: arrays swift uiimage nsdocumentdirectory

我正在尝试在 DocumentDirectory 路径中存储一系列图片 这是我存储图像的代码

 let img = photo //Change to be from UIPicker
    let data = UIImagePNGRepresentation(img!)!
    do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        try data.writeToFile("\(documentsPath)(myImage)", options: [])

    } catch {
        print("Error")
    }

这就是我获取图像的方式

  override func viewDidLoad() {
    super.viewDidLoad()

    do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let readData = try NSData(contentsOfFile: "\(documentsPath)(myImage)", options: [])
        let retreivedImage = UIImage(data: readData)
        image = retreivedImage
        photos.append(image!)

    }

    catch {
        print("Error")
    }

我的问题是当我保存第一张图片时我可以加载它但当我添加1张图像并保存时我无法重新加载

1 个答案:

答案 0 :(得分:0)

我认为这会对你有所帮助。这段代码对我有用。

您可以使用swift3.0

将图像下载并保存到文档目录,如下所示
R.layout.appwidget

var directoryPath:String {

TestClock

///将图像添加到文档目录

func addImage(_ image:UIImage,name:String) - >布尔{

R.id.textClock

func fetchImage(name:String) - > UIImage的? {

/// Get Document directory path