Firebase Database & Swift: Save location data in an array - ios

Hi all I am having a hard time saving coordinates in an array on Firebase. Basically I would like to track my location and save the Latitude and Longitude whenever there is a change in location.
This is what I currently get:
"-R359orfmkXiwERe948fk" : {
"coordinates" : {
"-S6O96394fXd0489fj" : {
"lat" : Lat1,
"long" : Long1
},
"-S6496SX235Hh12G893sb" : {
"lat" : lat2,
"long" : long2
},
"-F6O3941SwKZ5cA29038kdsg" : {
"lat" : lat3,
"long" : lat3
},
While This is the form I would like to get:
"-385fjAhm85fwERe948fk" : {
"coordinates" : [ [ Lat1,Long1], [Lat 2, Long2], [Lat 2, Long3]]
Using Firebase RealTime database and Swift 3

Firebase has no native support for arrays.
Instead of expecting Firebase to return you an array, I suggest writing a transformation method for your Swift model object, that you can use when you query Firebase, which converts the dictionary you currently receive into an array that you can then utilize throughout your app.
You will need a similar transformation that will then convert your array back to that dictionary format for updating Firebase.

Related

How to extract data from JSON with Alamofire

I use the Alamofire library this way:
Alamofire.request(.POST, "http://www.somesample.com/getData.php", parameters: ["user":"charles"]).responseJSON{jsonData in
var theData = jsonData.result.value
If I debug print the theData variable, it throws something like:
[
{
"userId" : "61",
"userPicture" : "147884767502.jpg",
"wasId" : "80",
"favorite" : "0",
"message" : "how are you?",
"username" : "paco",
"date" : "13\/10\/2015 03:44PM",
"userPhrase" : "hello"
"repliesNumber" : 2
},
{
"userId" : "3",
"userPicture" : "149181897286.jpg",
"wasId" : "5",
"favorite" : "0",
"message" : "let's go!",
"username" : "loliFlower",
"date" : "30\/08\/2015 07:48PM",
"userPhrase" : "ciiiii!",
"repliesNumber" : 3
}
]
I usually use SwiftyJSON so I write (even I use a for loop to walk to every single index of the array the SwiftyJSON makes:
var myData = JSON(theData.result.value)
print(myData[0]["username"].stringValue)
But what if I don't want to use SwiftyJSON library anymore? what is the native way to do this?
I recommend that you use code generation to create native models out of the json response, this will save your time of parsing by hand and reduce the risk of errors due to mistaken keys, all elements will be accessible by model properties, this will be purely native and the models will make more sense rather checking the keys. Check http://www.json4swift.com and let me know if you require further help in initiating the object from your json response. (make sure you enter the actual json response and not the printed object as that in your question)

RestKit JSON Mapping

I have given JSON and cannot parse partial data. It seems dictionary into dictionary:
{
"products": [
{
"id": 6796,
"title": "my title",
"description": "desc",
"code": "12345",
"valueType": "null",
"discounts": [
{
"minPrice": null,
"maxPrice": null,
"value": 20,
"avail": false
}
]
}
]
}
I am using the latest version of RESTKit but I cannot properly parse under discounts.
my RestKit settings are:
responseMapping.addAttributeMappingsFromDictionary([
"id" : "id",
"code" : "code",
"title" : "title",
"valueType" : "valueType",
"description" : "desc",
"discounts.minPrice" : "minPrice",
"discounts.maxPrice" : "maxPrice",
"discounts.value" : "value",
"discounts.avail" : "avail",
])
but all values below discounts always return Nil. What I am doing wrong?
You can't directly map using discounts.XXX because discounts is an array and you have no way to index into that array and extract a single value.
You either need to change the source JSON to compress the values out of the dictionary, or create a custom object that you can map each item in the discounts array to.
Technically you could map the whole discounts array, which would give you an array of dictionaries, that you could then unpack in the setter method, but the array of custom objects is usually a better approach.

How to access data in array in JSON

JSON:
{
"projects":[
{
"id":113,
"name":"Mobile app Android",
"description":"",
"created_on":"2014-10-03T16:53:56+02:00",
"updated_on":"2014-12-03T16:59:45+01:00"
},
{
"id":142,
"name":"Mobile app iOS",
"created_on":"2014-12-11T18:30:55+01:00",
"updated_on":"2014-12-11T18:30:55+01:00"
},
{
"id":52,
"name":"Test project",
"identifier":"grafikr",
"description":"",
"created_on":"2013-10-14T17:21:33+02:00",
"updated_on":"2014-10-10T17:40:47+02:00"
},
{
"id":37,
"name":"Sample project",
"identifier":"grafikf",
"description":"",
"created_on":"2013-09-18T16:31:25+02:00",
"updated_on":"2013-09-26T13:11:58+02:00"
}
],
"total_count":4,
"offset":0,
"limit":25
}
It is easy to access for example name of the first project (with name Mobile app Android) by var name = json["projects"][0]["name"].stringValue
But how do I access all names in SwiftyJSON? If I make a variable var projects = json["projects"], it gives me:
[
{
"id" : 113,
"created_on" : "2014-10-03T16:53:56+02:00",
"name" : "Mobile app Android",
"description" : "",
"updated_on" : "2014-12-03T16:59:45+01:00"
},
...
Now I don't have a problem with making a NSDictionary from data anymore, but this drives me crazy.
There's a lot going on in your code sample—perhaps too much to be addressed by a single Stack Overflow question / answer.
I would strongly recommend going back to Apple's resources for Swift and iOS application patterns. Topics to revisit would include synchronous versus asynchronous programming, authentication, and using data sources with table views.
This should probably work. Your json also contains "total_count", which looking at it, I assume that's the count of the number of projects. Pull that count out, loop over till the count and fetch the name.
var names = [String]()
let count = json["total_count"].int
for index in 0..<count {
let name = json["projects"][index]["name"].string
names.append(name)
}
Why not use SwiftyJSON the Swifty way???
Try this:
let names = json["projects"].arrayValue.map {
$0["name"].stringValue
}

RestKit MongoDB location data mapping

I am having trouble understanding how to Map location Data stored in Mongo DB with RestKit.
Here is the data I will be mapping in JSON
{ "name" : "TestPoint2", "media_resource" : "tester", "added" : ISODate("2012-10-10T23:00:00Z"), "loc" : { "type" : "Point", "coordinates" : [ -33.1, 12.54 ] }, "comments" : [ ], "tags" : [ ]}
The main point I am struggling with is mapping the "coordinates" of "loc"
To begin with, I'd treat the coordinates as they are represented in the JSON and store them as numbers in an array. If your object / entity has an array property / transformable attribute then you can just map the coordinates into that wholesale. You can then add accessor methods / transient attribute(s) which access that coordinate information and provide a nicer interface to get the lat/long than indexing into an array.

Rails: JSON Parsing a URL for later use

I'm trying to accomplish something really easily but I could not solve it to my beginner level in rails. The question is how do you assign a JSON objects attribute to a rails object.. I'm trying to send a request to Google Map's URL with some parameters. Without JSON parsing it works just fine, however when I try to parse it, I receive many errors. The regular JSON response from Google when I query the URL ([http://maps.googleapis.com/maps/api/directions/json?origin=40.983204,29.0216549&destination=40.99160908659266,29.02334690093994&sensor=false][1]) is like down below;
{
"routes" : [
{
"bounds" : {
"southwest" : {
"lat" : 40.98289,
"lng" : 29.02054
},
"northeast" : {
"lat" : 40.99148,
"lng" : 29.02388
}
},
"summary" : "Mühürdar Cd",
"waypoint_order" : [],
"legs" : [
{
"start_location" : {
"lat" : 40.98322,
"lng" : 29.02166
},
"distance" : {
"text" : "1.3 km",
"value" : 1324
},
And goes on.
The code I have to get the "summary" attribute is;
#request = Net::HTTP.get(URI.parse('http://maps.googleapis.com/maps/api/directions/json?origin=40.983204,29.0216549&destination=40.99160908659266,29.02334690093994&sensor=false'))
#result=JSON.parse(#request)["routes"]["summary"]
I wanted to ask what would be the proper way for me to get the summary attribute from the response?
hash['routes'][0]['legs'][0]['duration']['text']
would allow you to access Text and
hash['routes'][0]['legs'][0]['duration']['value']
the Value. Just try
hash['routes'][0]['legs'][0]['duration'].class
to see what type it is and access it accordingly

Resources