【发布时间】:2019-02-10 15:03:39
【问题描述】:
我正在制作一个应用程序,您可以在其中发布图像并将其显示在另一个页面上。我想将它保存到数据库中,但我不知道最好的方法。
【问题讨论】:
标签: swift database xcode sqlite
我正在制作一个应用程序,您可以在其中发布图像并将其显示在另一个页面上。我想将它保存到数据库中,但我不知道最好的方法。
【问题讨论】:
标签: swift database xcode sqlite
您可以使用
将图像保存在文件夹中func saveImage(image: UIImage) -> Bool {
guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent("fileName.png")!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
你可以用这个方法得到你的图像:
func getSavedImage(named: String) -> UIImage? {
if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
}
return nil
}
【讨论】:
您可以在swift中使用核心数据来保存图片。 Core Data 是 Apple 在 macOS 和 iOS 操作系统中提供的对象图和持久化框架。 通过使用核心数据,您可以轻松访问 sqlite 数据库。
使用 Core Data 在 Sqlite 中保存图像参见saving-picked-image-to-coredata
【讨论】:
您将图像保存在设备中,并将该图像的路径保存在 Sqlite 中。
此链接了解如何在设备中保存图像Saving image and then loading it in Swift (iOS)
【讨论】: