Joseph
Joseph

Reputation: 873

Save Image (SwiftUI) to Realm database

I am using SwiftUI and Realm.

I want to save an Image to the database. The image is a photo taken from the device's camera and is not stored in the gallery.

It's my understanding that I need to convert the image to NSData, but I can only find syntax that works with UIImage.

I tried

let uiImage: UIImage = image.asUIImage()

but get this error:

Value of type 'Image?' has no member 'asUIImage'

What am I doing wrong here, how can I have an Image to Realm local database?

EDIT: Thanks for the suggested "possible duplicate", but no: the duplicate (which I have already seen prior to making my post) is for UIImage (UIKit). I am using Image (SwiftUI).

Upvotes: 1

Views: 751

Answers (1)

Isaaс Weisberg
Isaaс Weisberg

Reputation: 2824

The struct Image is only a building block for the UI in Swift UI and it is not an object that represents the literal image, but rather something that displays some image.

The common approach, is to see how you create Image - where do you get the actual image from - and to use the source, the image itself to save it.

Just as side note, I wanted to mention that storing data blobs in Realm database can be extremely slow and more commonly used and fast approach is to write files to disk and to store only the names of those files in the database.

Elaborating on this approach, you can:

  • create a folder to store your images in Library path in user domain mask

You can read about iOS Sandbox file system and where you can store stuff at Apple File System Programming Guide.

For our purposes, it will suffice to this method.

let imagesFolderUrl = try! FileManager.default.url(for: . applicationSupportDirectory, in: .userDomainMask)
    .appendingPathComponent("images_database")
  • You should check if this directory exists and create it if it doesn't - there's plenty of information about this online.
  • Then, when you have an image Data, you give it a name, you create a URL that will point to where it will be stored and then you write it.
let imageData: Data
let imageName = "some new name for this particular image - maybe image id or something"

let imageUrl = imagesFolderUrl.appendingPathComponent(imageName)
imageData.write(to: url) // Very slow operation that you should perform in background and not on UI thread
  • Then, you store the name of the image in the Realm database
  • Then, when you pull a record from Realm database and see the name of the image, you can construct the url again and read a Data from it
let record: RealmRecord
let imageName = record.imageName
let url = imagesFolder.appendingPathComponent(imageName)
let data = Data(url: imageName)

That's overly simplifying it.

Upvotes: 3

Related Questions