在Swift中从领域加载图像路径的问题

时间:2017-01-09 00:17:53

标签: ios swift uiimage 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。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

试试这个:

// 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

}

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