在 Swift 中从 Realm 加载图像路径时出现问题



在我的应用程序中,我将图像存储在本地存储中,并将该图像的路径保存在我的 Realm 数据库中。现在我在从该路径加载此图像时遇到问题?

这就是我保存数据库路径的方式:

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory,nsUserDomainMask, true)
let dirPath = paths.first

    let imageURL1 = URL(fileURLWithPath: dirPath!).appendingPathComponent("refuge1.jpg")
    let med1 = Meditation()
    med1.name = "Refuge"
    med1.count = 0
    med1.targetAmount = 111111
    med1.malasStep = 108
    med1.imagePath = imageURL1.path
    med1.id = 1

我试图从这条meditation.imagePath路径中获取图像很简单。我仔细检查了路径,图像是否仍然无法使用此路径设置图像,是否缺少某些内容?

在调试模式下,我看到这个:

Meditation {
name = Refuge;
count = 0;
targetAmount = 111111;
malasStep = 108;
imagePath = /Users/macbook/Library/Developer/CoreSimulator/Devices/2E25309F-D6A9-41C3-9EF4-67203142172C/data/Containers/Data/Application/F198640B-3C72-4F9C-8173-FB00D3ABEC15/Documents/refuge1.jpg;
id = 1;}

但是我的可变图像在调试模式下仍然为零

// Configure the cell...
    cell.nameOfMeditation.text = meditation.name
    cell.countOfMeditation.text = String(meditation.count)
    let image = UIImage(contentsOfFile: meditation.imagePath)
    cell.imageForMeditation.image = image
    return cell

我看到冥想和声音的名称,机器人没有OMG。

不建议将文件的绝对文件路径保存在 iOS 应用程序中(即包括 /Users/macbook/Library/Developer/... 在内的所有内容)、Realm 或其他任何地方。

出于安全原因,iOS 设备会在启动之间重命名 UUID 文件夹名称。这意味着,虽然文件夹路径在保存时有效,但以后不会有效。

相反,建议只保存文件的相对路径(例如,它相对于Documents文件夹的位置)。在这种情况下,它只是 /refuge1.jpg ),然后根据需要通过请求Documents目录路径来动态构建绝对路径。

试试这个:

// Use these convenience methods if you do a lot of saving and loading
func getDocumentsURL() -> URL {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    return documentsURL
}
func fileInDocumentsDirectory(_ filename: String) -> String {
    let fileURL = getDocumentsURL().appendingPathComponent(filename)
    return fileURL.path
}
func saveRefugeOne(image: UIImage) {
    // Create a file name, and then save the path in your documents with that name
    let imageFileName:String = "refuge1.jpg"
    let imagePath = fileInDocumentsDirectory(imageFileName!)
    saveImage(image, path: imagePath)
}
func loadRefugeOne() -> UIImage? {
    // Get the image back
    let imageName:String = "refuge1.jpg"  // Or whatever name you saved
    let imagePath = fileInDocumentsDirectory(imageName)
    if let loadedImage = self.loadImageFromPath(imagePath) {
         return loadedImage
    } else { 
        print("Couldn't Load: (imageName)") 
        return nil
    }
}
// This will be your method to save image
func saveImage(_ image: UIImage, path: String ) {
    //If you want PNG use this let pngImageData = UIImagePNGRepresentation(image)
    // But since you mentioned JPEG:
    if let jpgData = UIImageJPEGRepresentation(image, 1.0) {
        try? jpgData.write(to: URL(fileURLWithPath: path), options: [.atomic])
    }
}
// This will load image from saved path. Make sure to store the path
// somewhere. This makes it easier to save images locally. You can 
// save the image in the documents directory, and then just save the
// path in CoreData or something similar.
func loadImageFromPath(_ path: String) -> UIImage? {
    let image = UIImage(contentsOfFile: path)
    if image == nil {
        print("couldn't find image at path: (path)")
    }
    return image
}

希望这会有所帮助。这是我经常使用的方法,当我按照自己的步骤正确操作时,它就像一个魅力;-)

最新更新