How to upload images to MongoDB Realm using SwiftUI

Along with text, MongoDB Realm allows developers to upload images to a local Realm database.

You can either upload the image to an open-source image uploader, like Imgur, and then download it back to cache it, or you can store the image locally in your Realm database. The latter has the advantage that it does not require Internet connectivity.

Now let’s directly store the image to a local Realm database within an iPhone.

You cannot directly upload an image to Realm, so you’ll have to convert it to NSData. Since Cocoa-Realm still uses Objective-C, it will support NSData conversion to UIImage, and vice versa.

Conversion process

  • Create an Identifiable, Object class, with an ID parameter and an NSData parameter for your image.
class UserData: Object, Identifiable {
    @objc dynamic var id: String?
    @objc dynamic image: NSData?
}
  • Now create a function to upload this image to Realm, where your image would be a parameter. You need an image picker to pick an image from the default iOS gallery.
fun uploadImage(image: UIImage){
    let data = NSData(data: image.jpegData(compressionQuality: 0.9)!)
    var userData = UserData()
    userData.image = data
    
    let realm = try! Realm()
    
    try! realm.write {
        realm.add(userData)
    }

}
  • Now you need to call this function within your view and pass the image that you want to upload from the image picker.
uploadImage(image: myImage)

Display the NSData as UIImage

  • Create ForEach, pass the result, and then simply get the image into the Image() widget. You can now simply pass the image as Data and Swift automatically converts this to a UIImage().
ForEach(data, id: \.self) { item in 
    Image(uiImage: UIImage(data: item.image! as Data)!)
}
  • You can now view your image. This allows your users to keep data within the device itself, rather than having to keep uploading it to an online server, and then keep downloading it again and again based on access to an internet connection.

  • You can also set a parameter incase you do not want to upload heavy images by simply calling the NSData length and then setting it as break in case the size exceeds.

if userData.image.length > 100000 {
    print("file too heavy, choose a lower resolution file.")
}

Free Resources