I am developing iOS project which uses Firebase database.
I have a observer to observe new data added to my Firebase database:
rootRef.observeEventType(.childAdded, withBlock: {(snap) in
// I try to access "positions" like this
if let mySnap = snap {
let positions = mySnap.childSnapshot(forPath: "positions").value as? Array
// But the positions is nil
})
The snap received is like this (It is print(snap)):
Optional( Snap (-KWoKFfKZOkFyoLI9at_) {
positions = {
0 = {
x = 80;
y = 212;
};
1 = {
x = 80;
y = "212.5";
};
10 = {
x = 83;
y = 229;
}
};
});
What is the right way to access "positions" data that get from firebase database?
As you have added response of mySnap.childSnapshot(forPath: "positions").value in comment it is type of Array of Dictionary so type cast it to [[String: Any]].
let positions = mySnap.childSnapshot(forPath: "positions").value as? [[String: Any]]
Related
Below I have some data in firestore.
I have a an array in the _geoloc field. Each of those indexes have latitude and longitude coordinates. So using SWIFT I want to be able to only get the lat and lng coordinates at index 0 and pass them to individually to a string. I have been researching for days and I am stuck. I have tried to create a new array of strings or an AnyObject array and I just get stuck with retrieving the data I need at index 0, and passing only those 2 lat/lng coordinates to string values. I have several failed snippets of code I could post.
Here is a snippet of what I was attempting to do: (I am really new to firebase so the code is a bit ugly as I am just trying to figure this out)
Firestore.firestore().collection("users").document("626").getDocument { (document, error) in
if let document = document {
// let geo_array = document["_geoloc"]
var yourArray = [String]()
// let geo_location = [geo_array] as [AnyObject]
let array: [Any] = document["_geoloc"] as! [Any]
let tmpArray = array.map({ return String(describing: $0)})
let string = tmpArray.joined(separator: ",")
yourArray.append(string)
print(yourArray[0])
You just need to cast your object from Any to an array of dictionaries and get the first property:
Firestore.firestore().collection("users").document("626").getDocument { document, error in
if let document = document {
var yourArray: [String] = []
if let location = (document["_geoloc"] as? [[String:Double]])?.first,
let latitude = location["lat"],
let longitude = location["lon"] {
let coordinate2d = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
yourArray.append("Latitude: \(location.latitude), Longitude: \(location.Longitude)")
}
}
}
Maybe first declare this:
var firstPositionValues = [AnyObject]()
Then get it like this:
let db = Firestore.firestore().collection("users").document("626")
db.getDocument { (document, error) in
if let document = document {
let geo_location = document["_geoloc"] as [AnyObject] // <- this is all of them in the document
var initialValues = geo_location[0] // <- here are your lat and lng at position 0
self.firstPositionValues = initialValues
}
Hope I understood correctly good luck.
I've been stuck all day, I'm trying to implement a chart on my app that has to collect some data from my firebase database to use them to populate the chart.
I've try this code to get the data from the database:
let userID = Auth.auth().currentUser?.uid
let bslChecksDB = Database.database().reference().child("BSL Checks").child(userID!)
bslChecksDB.observe((.childAdded)) { (snapshot) in
print(snapshot)
let snapshotValue = snapshot.value as! [String : [String: String]]
print(snapshotValue)
self.arrayOfDic = Array(snapshotValue.values)
for i in 0...self.arrayOfDic.count - 1 {
self.snapshotDictionary = self.arrayOfDic[i]
let date = self.snapshotDictionary["Date"]!
let time = self.snapshotDictionary["Time"]!
let bsl = Double(self.snapshotDictionary["BSL"]!)
let unit = self.snapshotDictionary["Unit"]!
let dateTime = "\(date) at: \(time)"
self.dateTimeArray.append(dateTime)
self.bslDataArray.append(bsl!)
self.uuuuDataArray.append(unit)
}
I try to print the various arrays to see if they were made and they were, so no problem (i thought). then when I proceed to upload those data on the chart, they disappear.... It seems like my arrays are wiped out as soon as they are made! What is wrong?
for i in 0...self.dateTimeArray.count - 1 {
ChartFormatter().array.append(self.dateTimeArray[i])
}
print("array")
print(ChartFormatter().array)
}
var lineChartEntry = [ChartDataEntry] ()
print(dateTimeArray.count)
for i in 0...dateTimeArray.count - 1 {
let value = ChartDataEntry(x: Double(i), y: bslDataArray[i])
lineChartEntry.append(value)
}
let line1 = LineChartDataSet(values: lineChartEntry, label: "BSL")
line1.colors = [NSUIColor.blue]
let data = LineChartData ()
data.addDataSet(line1)
chtChart.data = data
chtChart.chartDescription?.text = "My graph"
Since this is the first time I implement a chart on my app, could you please explain how to populate the chart with data from a firebase database? thanks
I want to store data into object form using swift language.The data structure of the data base is like
collection/
document/
collection/
document1/:
Invitess1(object) :
name :"santosh"
phone :1234567890
Invitee2(object) :
name :"sam"
phone:1234654768
.....
document 2/
Initee1(object) :
name:"red"
phone:4654343532
.......
is it possible to store data like this? if possible how to do it? i tried like this :
for var i in 0..<n { // n is no.of selected contacts
for var j in i...i {
print("amount is \(d[i])")
print("phone number is \(num[j])")
let dataToSave:[String: Any] = ["name" :"vijayasri",
"PhoneNumber":num[j],
"Amount": d[i],
]
}
}
var ref:DocumentReference? = nil
ref = self.db.collection("deyaPayUsers").document("nothing").collection("Split").addDocument(data: dataToSave){
error in
if let error = error {
print("error adding document:\(error.localizedDescription)")
} else {
print("Document ades with ID:\(ref!.documentID)" )
}
}
}
But it doesn't work. How to do it..
Your example code is never going to work as intended since dataToSave is overwritten every iteration of the j loop. Your inner j loop probably has a typo at i...i
To store multiple objects in one document, create the document in Swift with multiple objects in it. Since you know how to encode your object as [String:Any], just take those dictionaries combine into a larger [String:Any]document.
I would change your code to be more like:
var dataToSave: [String:Any] = []()
for var i in 0..<n { // n is no.of selected contacts
var inProcess: [String:Any] = []()
for var j in i...i {
print("amount is \(d[i])")
print("phone number is \(num[j])")
let detail: [String: Any] = ["name" :"vijayasri",
"PhoneNumber":num[j],
"Amount": d[i]]
inProcess["NextKey\(j)"] = detail
}
dataToSave["SomeKey\(i)"] = inProcess
}
var ref:DocumentReference? = nil
ref = self.db.collection("deyaPayUsers").document("nothing").collection("Split").addDocument(data: dataToSave){
error in
if let error = error {
print("error adding document:\(error.localizedDescription)")
} else {
print("Document ades with ID:\(ref!.documentID)" )
}
}
}
This is my JSON data, how can I get src data in 0 in pickArray?
"pickArray" : "{\"0\":{\"src\":\"https:\/\/fb-s-d-a.akamaihd.net\/h-ak-xpl1\/v\/t1.0-9\/p720x720\/18010403_1525007564199498_8009700960533638318_n.png?oh=25dbc9c1522dcfdd1d15cdd3e8c0c7da&oe=59997685&__gda__=1502470695_f212ade003e9b1c4ddc6a3ab6cc9e7e7\",\"width\":720,\"height\":720}}"
If I do it like this:
let dataArray = json["pickArray"]
print("dataArray = ",dataArray)
dataArray = {"0":{"src":"https://fb-s-d-a.akamaihd.net/h-ak-xpl1/v/t1.0-9/p720x720/18010403_1525007564199498_8009700960533638318_n.png?oh=25dbc9c1522dcfdd1d15cdd3e8c0c7da&oe=59997685&__gda__=1502470695_f212ade003e9b1c4ddc6a3ab6cc9e7e7","width":720,"height":720}}
But if I do it like this, show null:
let srcArray = dataArray["0"]
print("srcArray = ",srcArray)
I'm using swift3.0
Its looks like that with key pickArray you are having JSON response in String so get that string and convert it data and get JSON from it and then get src from it.
let stringResponse = json["pickArray"].stringValue
if let data = stringResponse.data(using: .utf8) {
let pickArray = JSON(data: data)
//Now access the pickArray to get the src
var sortedKeys = [String]()
if let allKeys = pickArray.dictionaryObject {
sortedKeys = Array(allKeys.keys).sorted { $0.compare($1, options: .numeric) == .orderedAscending }
}
for key in sortedKeys {
print(pickArray[key]["src"].stringValue)
print(pickArray[key]["width"].intValue)
print(pickArray[key]["height"].intValue)
}
}
let srcArray = dataArray["0"].dictionaryObject!
print("srcArray = \(srcArray)")
Now you can access element of "0" value as like below. Hope this work for you.
let jsonScr = JSON(srcArray)
let srcURL = jsonScr["scr"].stringValue
I am parsing twiter search api json data with NSJSONSerialization.Requirement is to search tweets by hashtag.In Twitter api console tool I am correctly getting data about 15 tweets.
written code is
if let results: NSDictionary = NSJSONSerialization .JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments , error: errorPointer) as? NSDictionary {
}
I am getting results value as
{
"search_metadata" = {
"completed_in" = "0.05";
count = 15;
"max_id" = 680240431771156480;
"max_id_str" = 680240431771156480;
"next_results" = "?max_id=680240407322689535&q=%23ChristmasEve&include_entities=1";
query = "%23ChristmasEve";
"refresh_url" = "?since_id=680240431771156480&q=%23ChristmasEve&include_entities=1";
"since_id" = 0;
"since_id_str" = 0;
};
statuses = (
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Fri Dec 25 04:15:31 +0000 2015";
entities = {
hashtags = (
{
indices = (
0,
13
);
text = ChristmasEve;
},
{
which is incomplete.
I even tried using SwiftyJSon library but I am getting similar results.
Is there any way to get statuses/Tweet info value without using any external library?
Given the fact that you mentioned you are getting multiple tweets (15), the JSON data you're getting back from the API possibly is an array, not a dictionary. It's a good practice to handle both cases when you make network calls:
do {
let object = try NSJSONSerialization.JSONObjectWithData(data, options: [])
if let dictionary = object as? [NSObject: AnyObject] {
// Handle dictionary
} else if let array = object as? [[NSObject: AnyObject]] {
// Handle array
}
} catch {
}