Mariah Mariah - 2 months ago 18
Swift Question

Retrieving images to 3 image views (Firebase and Swift)

From this node in JSON structure:

{
"Devices" : {
"WDREMca1BOcaaW457Mg8ankzId32" : {
"Device1" : {
"Category" : "",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : "https://firebasestorage.googleapis.com/v0/b/jabeerah-c27c3.appspot.com/o/Devices_Images%2F5F4E0AC2-8279-4CC4-AE99-E797655D4331.png?alt=media&token=5823ed16-e8ff-4b85-8a64-bfb00b965785"
},
"Device2" : {
"Category" : "",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : "https://firebasestorage.googleapis.com/v0/b/jabeerah-c27c3.appspot.com/o/Devices_Images%2FF9E2EF8D-44B3-4BE6-9020-81D190A45AA3.png?alt=media&token=af17e9a5-53f4-4054-9496-fb86d1508a6f"
}
},
"a4gbFozO4gTZE6QT60b6qxQDriw2" : {
"Device1" : {
"Category" : "أخرى",
"Description" : "mmm",
"DeviceName" : "mmm",
"ImageUrl" : "https://firebasestorage.googleapis.com/v0/b/jabeerah-c27c3.appspot.com/o/Devices_Images%2FCF13F154-2B5F-4926-A979-2E187BD0E504.png?alt=media&token=bf1b876f-9f9a-4e78-9e8d-98d017fd0404"
}
}


I'm trying to retrieve the users' pictures to his/her profile.
The profile view has 3 image views (Since each user can have only 3 devices or less).

In viewDidLoad function I have made this:

if ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device1") != nil {

ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device1").observe(.value , with: {snapshot in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
self.ImageViewOne.downloadedFrom(link: ImageUrl!)

})

} else {
//
}
if ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device2") != nil {

ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device2").observe(.value , with: {snapshot in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
self.ImageViewTwo.downloadedFrom(link: ImageUrl!)
})

} else {
//
}
if ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device3") != nil {

ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device3").observe(.value , with: {snapshot in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
self.ImageViewThree.downloadedFrom(link: ImageUrl!)
})

} else {
//
}


But this actually gave me a signal SIGABRT error in

let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String


Not sure why this happens!

For downloadedFrom Function, I'm using the extension from this answer

Answer

Try replacing :-

 let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String

To -

 if let deviceDict = snapshot.value! as? [String : AnyObject]{
     let imageUrl = deviceDict["ImageUrl"] as! String
     self.ImageViewThree.downloadedFrom(link: ImageUrl!) 
     }