【问题标题】:Error when trying to get images from DocumentDirectory path尝试从 DocumentDirectory 路径获取图像时出错
【发布时间】:2017-01-13 02:50:51
【问题描述】:

我正在尝试在 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 张图片并保存我无法重新加载它”?
  • 你是怎么做的?
  • 我的意思是当我选择第一个图像并关闭应用程序并再次打开它时,我使用 tableview 显示图像数组,图像将显示,但是当我将另一个图像添加到数组并关闭应用程序并再次打开它没有图像显示

标签: arrays swift uiimage nsdocumentdirectory


【解决方案1】:

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

您可以使用 swift3.0 下载图像并将其保存到文档目录,如下所示

/// Get Document directory path

var 目录路径:字符串 {

    let baseUrl = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

    print("Base Url: \(baseUrl.first!)")

    return baseUrl.first!
}

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

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

    var path = directoryPath

    path.append("/\(name)")

    return FileManager.default.createFile(atPath: path, contents: UIImageJPEGRepresentation(image, 1.0), attributes: nil)
}

/// fetch a image from document directory

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

    var imagePath = directoryPath

    imagePath.append("/\(name)")

    if  FileManager.default.fileExists(atPath: imagePath) {

        return UIImage(contentsOfFile: imagePath)!

    } else {

        return nil

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多