This is part of JSON my API returns, I don't know how to get that and store in Realm table?
"images": {
"image1": {
"url": "http://www.example.com/900150983cd24fb0d6963f7d28e17f72.gif",
"path": "data/2clb91218/900150983aassfb0d6963f7d28e17f72.gif",
"alt": "YWJj"
},
"image2": {
"url": "http://example/tex/fbce4a1ebe576539394e9493e30c7e5e.gif",
"path": "data/2clb91218/900150983cd24fb0d6963f7d28e332g22.gif",
"alt": "Yaaase22"
},
"image3": {
"url": "https://example.amazonaws.com/card/480_300/9/9jpul1218.jpg",
"path": "data/2clb91218/ewfregwrgw6963f7d28e17f72.gif",
"alt": "pic3"
}
}
NOTE : Don't test these urls, I didnt want to put real ones.
NOTE : In object 'Images', child-object's names are chaining so we have: 'image1' , 'image2' etc.
I have read on Stack Overflow that for storing arrays in RealmTable
, we need to use non-dynamic List<>
, so this is how I store image-urls in class:
var images = List<String>()
This is part of my responseJSON
function where I am trying to Get images from API, continue
is there just to Get another objects if images are unable to Get :
guard let images = data["images"] as? [String: Any?],
let image = images["image1"] as? [String: String],
let imageUrl = image["url"] as? String
else { print("error") ; continue }
This above works for 'image1', but what about other image names, how to handle them?
And one more problem - Images
object can return NIL if there are no images which can aslo happen. If it's nil, I want to put "null" in RealmTable's column 'images' of the type I mentioned above.
I hope you can fully understand me, if not, comment and I will try to explain better.
You need
guard let images = data["images"] as? [String:[String:Any]] else { return }
let res = Array(images.values)
let urls = res.compactMap { $0["url"] as? String }
print("All urls : ",urls)