I've just started using Firebase for my Swift programming . I managed to fetch some data from the Json using the following :
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").child("Like").observeSingleEvent(of: .value, with: { (Snapshot) in
let Value = Snapshot.value as? Int
print(Value!)
})
However , I am trying to fetch the whole object first and then get the value of each element later . So here is my attempt but my app keeps getting terminated :
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").observeSingleEvent(of: FIRDataEventType.childAdded, with: { (snapshot) in
print(snapshot.children.value(forKey: "Like") as? Int)
print(snapshot.children.value(forKey: "Image") as? String)
})
Any idea where am I making a mistake ?
here is my Json :
{
"Posts": {
"1": {
"Post": {
"Poster_ID": "ID",
"Post_Time_stamp": "12:12:12AM",
"Image": "img.png",
"Video": "video.mov",
"Like": "3",
"Dislike": "0",
"Massage": {
"Massage_ID": "MSG_ID",
"Massager": "id",
"Massage_Time_stamp": "12:12:12PM",
"Massage_content": "comment"
}
}
},
"2": {
"Post": {
"Poster_ID": "ID",
"Post_Time_stamp": "12:12:12AM",
"Image": "img.png",
"Video": "video.mov",
"Like": "3",
"Dislike": "0",
"Massage": {
"Massage_ID": "MSG_ID",
"Massager": "id",
"Massage_Time_stamp": "12:12:12PM",
"Massage_content": "comment"
}
}
}
},
"User": {
"1": {
"User_name": "name",
"User_pass": "pass",
"User_avatar": "img.png"
},
"2": {
"User_name": "name",
"User_pass": "pass",
"User_avatar": "img.png"
}
}
}
Try printing snapshot first and see if you are able to retrieve anything if no, Try this
Use FIRDataEventType as .value instead of .childAdded. Since .childAdded is only fired when a child node is added to that reference node, .value retrieves the current value as that reference point..
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
print(snapshot.children.value(forKey: "Like") as? Int)
print(snapshot.children.value(forKey: "Image") as? String)
})
if you want to get the post object you need to access snapshot.value also observe for value event instead of childAdded.
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post")
.observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String:Any] {
print(dict["Like"] as? Int ?? 0)
}
})
Related
I'm saving this API response in Core Data successfully:
{
"data": [{
"result": {
"id": 5,
"key": "A",
"title": "some title",
"comments": "some comments",
"created_at": "2019-12-16 13:42:26",
"updated_at": "2019-12-16 13:42:26",
"deleted_at": ""
}
}, {
"result": {
"id": 7,
"key": "B",
"title": "some title",
"comments": "some comments",
"created_at": "2019-12-16 13:45:29",
"updated_at": "2019-12-16 13:45:29",
"deleted_at": ""
}
}]
}
And I'm able to retrieve it from Core Data, but I need to retrieve only the array that has "key": "A"
So I'm trying to do it this way but getting nothing returned:
func getResultA() -> [ResultsModel] {
var retrievedResults = [ResultsModel]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Results")
fetchRequest.predicate = NSPredicate(format: "key == %#", "A")
let result = try? privateContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
let id = data.value(forKey: "id") as? Int ?? 0
let key = data.value(forKey: "key") as? String ?? ""
let title = data.value(forKey: "title") as? String ?? ""
let comments = data.value(forKey: "comments") as? String ?? ""
retrievedResults.append(ResultsModel(id: id, key: key, title: title, comments: comments))
}
return retrievedResults
}
Here is the ResultsModel if it helps:
class ResultsModel {
let id: Int
let key: String
let title: String
let comments: String
init(id: Int, key: String, title: String, comments: String) {
self.id = id
self.key = key
self.title = title
self.comments = comments
}
}
I think I'm having a mistake using NSPredicate I need to filter only the array that have Key = A or B .
Can anyone point out the mistake please? Thank you in advance for your ideas and time!
Want to convert my json object into an array of just names so I can use the search bar to search for different names and filter it.
"data2": {
"id": 1,
"contacts": [
{
"name": "Molly",
"pictureUrl": "molly"
},
{
"name": "Cathy",
"pictureUrl": "molly"
},
{
"name": "Bob",
"pictureUrl": "bob"
},
{
"name": "Nick",
"pictureUrl": "clothes"
}
],
},
"error": 0,
"message": "Success"
This is the json file with the object:
var contact = [IndividualContact]()
init?(data2: Data) {
do {
if let json2 = try JSONSerialization.jsonObject(with: data2) as? [String: Any], let body = json2["data2"] as? [String: Any] {
if let contacts = body["contacts"] as? [[String: Any]] {
self.contact = ( contacts.map { IndividualContact(json2: $0) } )
//Expected: ["Molly", "Bob", "Cathy"]
}
}
I have a Firebase structure like this:
"userObjects" : {
"fP8g5kxrjnBhYTiUxjF6Pdc5xfgP" : {
"objectsInLists" : {
"603648351" : {
"Top" : true
},
"097598765" : {
"Roof" : true
}
}
},
I would like to get all true values under an objectID (097598765 is one objectID).
So I want check if 097598765 exists, and if it does I want to print "Roof"
This is as far I have come:
self.ref?.child("userObjects").child(userID!).child("objectsInLists").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(self.objectID) {
print(snapshot.value)
}
})
What you're looking for is queryOrderedByValue(), since you're looking to filter on the value of the child nodes that you're querying:
self.ref?.child("userObjects").child(userID!).child("objectsInLists/097598765")
.queryOrderedByValue().queryEqual(toValue: true)
.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
print(snap.key)
}
})
{ length = 30, contents = "something", count = 32.3 }
I need exact output in this bracket { } not in() or []
var array:Array<Any> = Array<Any>();
array.append(NSDictionary(object: singleItem.name, forKey: "name" as NSCopying));
array.append(NSDictionary(object: singleItem.planned_revenue, forKey: "planned_revenue" as NSCopying));
array.append(NSDictionary(object: singleItem.phone, forKey: "phone" as NSCopying));
array.append(NSDictionary(object: singleItem.description, forKey: "description" as NSCopying));
array.append(NSDictionary(object: singleItem.email_from, forKey: "email_from" as NSCopying));
array.append(NSDictionary(object: singleItem.probability, forKey: "probability" as NSCopying));
output
[{
name = "this is another";
}, {
"planned_revenue" = "0.0";
}, {
phone = "";
}, {
description = "Internal Notes";
}, {
"email_from" = "thomas.passot#agrolait.example.com";
}, {
probability = "20.0";
}]
I need like
[{ name = "this is another", "planned_revenue" = "0.0", phone = "", description = "Internal Notes", ..... }]
First, you need a dictionary, not an array of dictionaries. Using Swift, you can use Dictionary instead of NSDictionary (Dictionary<String, Any> or [String: Any]):
let dict: [String: Any] = [
"name": singleItem.name,
"planned_revenue": singleItem.planned_revenue,
"phone": singleItem.phone,
"description": singleItem.description,
"email_from": singleItem.email_from,
"probability": singleItem.probability
]
// If you need a NSDictionary, you can cast it
let nsDict = dict as NSDictionary
Take a look at Collection Types in the Swift guide and the Dictionary class reference for more information.
I have a callback function which retrieves stuff from a url however the information doesn't get stored into class variables.
var counts:Int?
var imagesComments : [NSArray] = []
loader.getFeed("1", completionHandler: { response in
if let dataArr = response["content"] as? NSArray{
for downloaded_images in dataArr{
if let image = downloaded_images as? NSDictionary{
let url = image["url"] as? String
// Get images and load into images
if let comments = image["comments"] as? NSArray{
dispatch_async(dispatch_get_main_queue()) {
self.imagesComments.append(comments)
}
}
self.loader.downloadImage(NSURL(string: self.baseUrl+url!)!, completionHandler: { response in
dispatch_async(dispatch_get_main_queue()) {
self.images.append(response)
self.pileView?.reloadContent()
}
})
}
}
}
})
After this code is run, I have a place where I print imagesComments and counts and both are empty/nil
JSON File:
{
"success": true,
"message": null,
"content": [{
"url": "6\/image_2.png",
"date_added": "2015-12-02 22:43:05",
"comments": ["Awesome Pic", "WOOHOOOOO THIS IS GREAT"],
"likes": []
}, {
"url": "2\/image_5.png",
"date_added": "2015-12-01 06:43:48",
"comments": ["EhHHHH"],
"likes": []
}]
}