无法使用文件路径Swift 4.2保存和加载图像

时间:2019-03-11 19:56:30

标签: swift core-data

我正在尝试将图像文件路径保存到CoreData中的字符串,然后将其重新加载到单独的viewController上。我现在没有收到任何错误。似乎可以很好地保存,除了图像未加载到UICollectionView中之外。

这是子视图控制器中保存文件路径的保存按钮。

@objc func saveDataButtonTapped(sender: UIBarButtonItem) {
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        let documentPath = documentsURL.path
        let filePath = documentsURL.appendingPathComponent("1.png", isDirectory: true)
        pet.profilePicPath = filePath.path

        do { 

            let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")

            for file in files {
                // Delete duplicate image if one already exists in this path
                if "\(documentPath)/\(file)" == filePath.path {
                    try fileManager.removeItem(atPath: filePath.path)
                }
            }
        } catch {
            print("Could not add image from document directory: \(error)")
        }
        do {
if let pngImageData = profilePicImageView.image!.pngData() {
                try pngImageData.write(to: filePath, options: .atomic)
            }
        } catch {
            print("couldn't write image")
        }
        pet.profilePicPath = documentPath
        PersistenceManager.shared.save()
        _ = navigationController?.popViewController(animated: true)
}

这是主视图控制器上预期要加载图像的cellForItemAt indexPath函数。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HorCell", for: indexPath) as? PRMainHorizontalCollectionViewCell else {
        return UICollectionViewCell()
    }
    let pet = pets[indexPath.row]
    if FileManager.default.fileExists(atPath: "\(String(describing: pet.profilePicPath))/1.png") {
        if let contentsOfFilePath = UIImage(contentsOfFile: "\(String(describing: pet.profilePicPath))/1.png") {
            cell.petImage.image = contentsOfFilePath
        }
    }
    return cell
}

0 个答案:

没有答案