【问题标题】:Loading an image saved to the Documents Directory only works once, then never loads again加载保存到文档目录的图像只能工作一次,然后永远不会再次加载
【发布时间】:2016-12-08 18:32:44
【问题描述】:

我正在编写一个应用程序,用户可以在其中选择要在应用程序中使用的图像,这些图像将被保存然后加载到表格视图中。我将图像的数据保存到文档目录,然后将数据路径作为属性保存到领域对象。然后我尝试使用保存的路径来加载其关联的图像。

现在,我正在保存(我认为是成功的,因为它会加载一次图像...),如下所示:

let image = imageField.image
let imageData = UIImagePNGRepresentation(image) as NSData?

let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let uuid = UUID().uuidString
let writePath = documentsDirectory.appendingPathComponent("\(uuid).png")

imageData?.write(toFile: writePath, atomically: true)

ownerPhoto.photoPath = writePath  //setting the path attribute of the object
ownerPhoto.owner = newOwner       //creating a relationship between the image and the owner

newOwner.title = titleTextField.text!
newOwner.ownerDescription = ownerDescriptionField.text!
newOwner.photos.append(ownerPhoto)

let realm = try! Realm()

try! realm.write {
    realm.add(newOwner)
    realm.add(ownerPhoto)
//I am creating and saving both the new Owner profile and their first photo at the same time here
}

保存后,它会转到 tableView。此 tableView 将显示所有者列表,以及我们刚刚保存的照片作为每个单元格的背景。我正在尝试这样做:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! tableCellTripTableViewCell

    let row = indexPath.row

    let firstPhoto = ownersArray[row].photos[0].photoPath
    //This is an array of all of the Owner objects of the app
    //firstPhoto will be equal to the path (String) that we just saved above

    cell.backgroundImage.image = UIImage(contentsOfFile: firstPhoto)
    return cell
}

目前,单元格仅在首次保存后才显示保存的图像。一旦我按下保存并转到 tableView,新创建的所有者将有他们的背景,但是一旦我重新启动应用程序,单元格就没有背景。为什么会消失?我做错了什么?

谢谢!

为将来阅读此内容的任何人编辑:

要解决此问题,请不要保存路径。只是文件名(uuid)。这样做:

ownerPhoto.photoPath = "\(uuid).png"

然后在 cellForRowAt 函数处:

let imagePath = getDocumentsDirectory().appendingPathComponent(firstPhoto)

cell.backgroundImage.image = UIImage(contentsOfFile: imagePath)

【问题讨论】:

    标签: ios swift uitableview uiimage


    【解决方案1】:

    永远不要存储完整路径。应用程序的沙盒会随着时间而变化。只需存储文件名。如果要获取文件的完整路径,请在运行时根据存储的文件名和 Documents 文件夹的当前值计算它。

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      相关资源
      最近更新 更多