从Realm保存并检索图像文件

时间:2017-10-08 08:47:30

标签: ios filesystems realm realm-mobile-platform save-image

写入文件系统允许用户在其设备上写入和检索字符串,图像等文件。

例如,我在运行模拟器时出现的应用程序中写入和检索的图像对于该应用程序包是唯一的,与我从设备中写入和检索的图像不同。

当我研究如何使用Realm编写和读取图像文件时,我被告知不要保存图像而是保存路径。图像太大而无法存储。得到它了。

但是我保存的文件路径自然会返回特定应用程序包的原生数据 - 或者返回nil。如果文件路径对于设备是唯一的,我如何编写和检索与Realm之间的图像文件/路径?我需要一个单独的图像阵列吗?

第一视图控制器

let planet = planets[indexPath.item]
cell.name.text = planet.name
cell.system.text = planet.system

  let imageData = (self.getDirectoryPath() as NSString).appendingPathComponent("image")
        if self.fileManager.fileExists(atPath: imageData) {

            // Populates every cell with the same image

            cell.earthImage.image = UIImage(contentsOfFile: imageData)    

            // returns nil

            cell.earthImage.image = UIImage(contentsOfFile: planet.image)
        } 

 // Retrieve directory path for image

func getDirectoryPath() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

第二视图控制器

  let planet = Planet()
        self.realm = try! Realm(configuration: config(user: SyncUser.current!))
        planet.name = self.name.text!
        planet.system = self.system.text!

  let imageData = (self.getDirectoryPath() as NSString).appendingPathComponent("person")
        if self.fileManager.fileExists(atPath: imageData) {
            self.earthImage.image = UIImage(contentsOfFile: imageData)

            // Why does this not write to realm?

            planet.image = imageData
        }

        try! self.realm.write {
            self.realm.add(planet)
        }

在这里,我是从secondViewController发布的,我希望在collectionView的{​​{1}}方法firstViewController中呈现这些值。

以下是模型:

numberOfItemsInSection_:)

0 个答案:

没有答案
相关问题