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 supportNSData
conversion toUIImage
, and vice versa.
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?
}
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)
}
}
uploadImage(image: myImage)
NSData
as UIImage
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.")
}