1

I would like to know if it is possible to save an image to realm database. If yes, how can I do that?

I understand Swift only!

Thank you in advance

M. Len-en
  • 11
  • 1
  • 2

2 Answers2

3

The best way to save images and other kind of data in this case is to store only the URL to the file in the database. Attention: URL does NOT mean a remote URL.

For example, if you want to persist your image, you can create a folder in the Documents folder, and save any image there, with a random name or whatever you prefer.

Here's how to access the Documents folder using Swift:

let documentsPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsPath = documentsPaths.first

Then in your Realm, store only the path to the file ("/images/1R9RI8S.jpg").

That way, you can always retrieve your image file by fetching the Documents folder, plus your Realm is not bloated with large data, plus the content of the Documents folder is backed up by iOS.

Gui Moura
  • 1,360
  • 1
  • 16
  • 26
  • Hmm, I would like to know what's wrong with this answer, why the down-votes. Isn't this one of the recommended methods to work images in realm? – fs_tigre Jun 04 '17 at 03:09
  • 2
    ¯\_(ツ)_/¯ maybe people REALLY wanted to know how to save the blob, and not best practices – Gui Moura Jun 12 '17 at 18:18
3

You can store images as NSData if images are small in size or less in numbers. However, if you have more images or large size store only paths. Look at the related answer link

Community
  • 1
  • 1
Anni S
  • 1,996
  • 19
  • 28