簡體   English   中英

加載保存到文檔目錄中的圖像只能進行一次,然后再也不會加載

[英]Loading an image saved to the Documents Directory only works once, then never loads again

我正在編寫一個應用程序,用戶可以選擇要在該應用程序中使用的圖像,該圖像將被保存,然后加載到表格視圖中。 我將圖像的數據保存到documents目錄,然后將數據路徑保存為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,新創建的所有者將具有其背景,但是一旦我重新啟動該應用程序,該單元格將沒有背景。 為什么消失了? 我究竟做錯了什么?

謝謝!

編輯以供日后閱讀:

要解決此問題,請不要保存路徑。 只是文件名(uuid)。 這樣:

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

然后在cellForRowAt函數中:

let imagePath = getDocumentsDirectory().appendingPathComponent(firstPhoto)

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

切勿存儲完整路徑。 應用的沙箱會隨時間變化。 只需存儲文件名即可。 如果要獲取文件的完整路徑,請在運行時根據存儲的文件名和Documents文件夾的當前值進行計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM