加载保存到文档目录的图像只能工作一次,然后再也不会加载

时间:2016-12-08 18:32:45

标签: ios swift uitableview uiimage

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

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

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,新创建的所有者将拥有他们的背景,但是一旦我重新启动APP,该单元格没有背景。为什么它会消失?我做错了什么?

谢谢!

编辑任何人在未来阅读:

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

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

然后在cellForRowAt函数:

let imagePath = getDocumentsDirectory().appendingPathComponent(firstPhoto)

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

1 个答案:

答案 0 :(得分:4)

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