how to add dictionary and get values - swift

sorry, I'm trying to add a json of type dictionary and get the values. I don't know if I'm doing it correctly, that's how it works for me, but when I get the values ​​of the function that the dictionary returns, my application doesn't get anything.
I tried to obtain this data in different ways. I don't know if someone could give me any idea, thank you.
let jsonLifevitPBM_200 = """
{
"result" : [
{
"id_d" : 55,
"id_c" : "0",
"data" : [
{
"Diastolic" : 85,
"ErrorCode" : -1,
"Systolic" : 120,
"Pulse" : 72
}
],
"date_s" : "2021-07-28 09:45:16.201"
}
],
"error" : 0,
"flags" : 0
}
"""
let jsonKelvin = Data(jsonLifevitPBM_200.utf8)
let jsonKelvinResult = try? JSONDecoder().decode(VitalSignTermometreResponse.self, from: jsonKelvin)
let temperature = jsonKelvinResult?.result[0].data[0].Temperature
let mode = jsonKelvinResult?.result[0].data[0].Mode
let unit = jsonKelvinResult?.result[0].data[0].Unit
if let tem = temperature , let mod = mode , let uni = unit {
labelsystole.text = "Error: \(tem)"
labeldiastole.text = "Error: \(mod)"
labelPulse.text = "Error: \(uni)"
} else {
labelResult.text = "Error Medisana BU 575 Connect"
}
Another way of trying to create the dictionary and get the data was this way, but I don't think it is in the correct way
let responseDevice : [String : Any] = [
"result" : [
"id_d" : 55,
"id_c" : "0",
"data" : [
"Diastolic" : 85,
"ErrorCode" : -1,
"Systolic" : 120,
"Pulse" : 72
],
"date_s" : "2021-07-28 09:45:16.201"
]
]
if let dat = responseDevice["result"] as? [String : Any] {
if let resultData = dat["data"] as? [String : Any] {
if let diast = resultData["Diastolic"] as? String ,
let systolic = resultData["Systolic"] as? String {
println("Result : \(diast) - \(systolic)")
}
}
}

I think the best way to do that is to use a third party library to get JSON and after that you can manage JSON values.
https://github.com/SwiftyJSON/SwiftyJSON

Related

Create dictionary with objects and array statically and get their value

I am trying to create a dictionary in a static way and obtain the data, but I am not correct. I mean because it is only an array of string and any, but in the image it has brackets and braces. Any help I will appreciate a lot, thanks for your time
let responseDevice : [String : Any] = [
"date_s" : "2021-02-18",
"id_c" : "4",
"id_d" : 1,
"data" : [
"Peso" : 34,
"Fc" : -1,
"Age" : 34,
"Name" : "July"
],
"flags" : 0,
"error" : 0
]
if let date_s = responseDevice["date_s"] as? String,
let dat = responseDevice["data"] as? [String : Any],
let peso = dat["Peso"] as? Int {
print(date_s)
print(peso)
}
print("log :\(responseDevice)")
result:
2021-02-18
34
log :["id_c": "4", "error": 0, "id_d": 1, "flags": 0, "date_s": "2021-02-18", "data": ["Peso": 34, "Fc": -1, "Age": 34, "Name": "July"]]
What you created is a Swift Dictionary. What you have on that image is JSON Object. It's not very clear what your goal is, so couple of basic pointers:
If you want to parse JSON into Dictionary, check this answer
If you simply want to include some JSON sample in your code (e.g. for testing), you can put it in triple quotes:
var myJSON = """
[paste your JSON here]
"""

Are there different solution how retrieve waypoints?

"-KHbCuQflKHrJiUmfpG0" : {
"waypoints" : {
"-KHbCuQflKHrJiUmfpG1" : {
"latitude" : 13.17078652595298,
"longitude" : -59.5775944578738
},
"-KHbCuQflKHrJiUmfpG2" : {
"latitude" : 13.15541190861343,
"longitude" : -59.57619643155932
},
"-KHbCuQg9W_tebl1pU66" : {
"latitude" : 13.148444967591,
"longitude" : -59.5589266947333
}
},
"subtitle" : "jamesrick",
"title" : "Highway",
"type" : "polyline"
},
I have this structure for lines in Firebase. How retrieve all data with also nested node waypoints?
ref.observeEventType(.Value, withBlock: { polylines in
if let objects = polylines.children.allObjects as? [FDataSnapshot] {
for object in objects {
polylineDictionary = object.values as? Dictionary<String, AnyObjects> {
// ? ? ?
}
}
}
})
Now I have access to title, subtitle, type but how obtain access to waypoints? When I use
`polylineDictionary["waypoints"] as? [String: [String:Double]]`
so this dictionaries are not ordered. Thanks for some advice.
This is how I would get the nested waypoints... it's basically by iterating through the keys... I would also add some error checking when grabbing the longitude and latitudes to make sure they're there, but this is the gist:
if let polylineDictionary["waypoints"] as? [String: [String:Double]] {
let waypoints = Array(polylineDictionary.keys)
for i in 0..<waypoints.count {
let waypointId = waypoints[i]
let latitude = polylineDictionary[waypointId]["latitude"]
let longitutde = polylineDictionary[waypointId]["longitude"]
}
}
It's not clear from the question about ordering; if you just want to get to the waypoints, it's pretty straight forward:
Assume your complete Firebase structure is:
root_node
"-KHbCuQflKHrJiUmfpG0" : {
"waypoints" : {
"-KHbCuQflKHrJiUmfpG1" : {
"latitude" : 13.17078652595298,
"longitude" : -59.5775944578738
},
"-KHbCuQflKHrJiUmfpG2" : {
"latitude" : 13.15541190861343,
"longitude" : -59.57619643155932
},
"-KHbCuQg9W_tebl1pU66" : {
"latitude" : 13.148444967591,
"longitude" : -59.5589266947333
}
},
"subtitle" : "jamesrick",
"title" : "Highway",
"type" : "polyline"
}
Suppose I want the data for this specific node, -KHbCuQflKHrJiUmfpG0
let nodeRef = rootRef.childByAppendingPath("-KHbCuQflKHrJiUmfpG0")
nodeRef.observeSingleEventOfType(.Value , withBlock: { snapshot in
print(snapshot.value) //prints everything in the node
let title = snapshot.value["title"] as! String //to get any element
print(title) //prints Highway
var waypoints = [String: [String:String]]() //dict to hold key:value, unordered
waypoints = snapshot.value["waypoints"] as! Dictionary
print(waypoints) //prints the 3 waypoints and their children (as a dict)
//get fancy and convert the dictionary to an array (which can be sorted)
let arr = waypoints.map {"\($0) \($1)"}
for point in arr {
print(point)
}
}

Json results to a string array in swift

Hello i've been trying to make a json request and some of its results i want to put it to an array of string.
So i have the following code
var arrRes = [[String:AnyObject]]()
var nameaRR = [String]()
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "https://graph.facebook.com/search", parameters: ["q": "", "type": "place", "center": "37.928319,23.7036673", "distance": "10000","limit": "1000", "access_token": "SomeToken", "expires_in": "5184000"])
.responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
//print(swiftyJsonVar)
if let resData = swiftyJsonVar["data"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
self.nameaRR = swiftyJsonVar["data"]["name"] as! [String]
print(self.nameaRR)
}
if self.arrRes.count > 0 {
self.kati.reloadData()
}
}
}
}
The JSON Resul is the following
{
"data" : [
{
"category_list" : [
{
"id" : "272705352802676",
"name" : "Outdoors"
},
{
"id" : "115725465228008",
"name" : "Region"
}
],
"id" : "552889064768971",
"name" : "Παλαιο Φαληρο", //This String i want to put in an Array
"category" : "Local business",
"location" : {
"street" : "",
"city" : "Palaión Fáliron",
"country" : "Greece",
"longitude" : 23.6944070162,
"zip" : "17562",
"latitude" : 37.9284637008,
"state" : ""
}
}
]
}
I get a warning
Cast from 'JSON' to unrelated type '[String]' always fails
But i'm stuck of how can i put all the Strngs to the array nameaRR.
Can anyone help me find my mistake? Thanks!
look do like that
if let resData = swiftyJsonVar["data"] as? [[String:AnyObject]] {
if let categorylist = resData["category_list"] as? [[String:AnyObject]]{
if let id = categorylist["id"] as? Int{
print(id)
}
}
}

Searching in Array of Dictionaries

I'm trying to search values in array of dictionaries which I get from JSON. I have a tableViewController with UISearchResultsUpdating. I found an example with array of Strings:
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF contains[c] %#", searchController.searchBar.text)
let array = tableData.filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
And I really don't know how to made search in array like this:
(
{
id = 3;
name = TestNewYork;
},
{
id = 2;
name = TestLA;
},
{
id = 1;
name = TestWashington;
}
)
my tableData = [] and filteredTableData must be an array too
Please, help!
You can use a simple filter function to do this...
tableData : [[String : String]] = ... // your JSON array of String, String dictionaries...
filteredTableData = tableData.filter{
dictionary in
return dictionary["name"] == filterString
}
Something like that anyway, not written Swift for a while.
You can wrap it in a function too...
func filter(array : [[String : String]], byString filterString : String) -> [[String : String]] {
return array.filter{
dictionary in
return dictionary["name"] == filterString
}
}
Or something. Not checked the code yet. Will be back if it doesn't work.
Checked in Playground and this works...
UPDATE
Changed to this...
let data = [
[
"id" : 3,
"name" : "a"
],
[
"id" : 4,
"name" : "b"
],
[
"id" : 5,
"name" : "c"
]
]
let filteredData = data.filter{
return $0["name"] == "b"
}
And it works. Just can't work out how to wrap in a function.
If you want to match the beginning of words...
let data = [
[
"id" : 3,
"name" : "Hello"
],
[
"id" : 4,
"name" : "Goodbye"
],
[
"id" : 5,
"name" : "Everybody"
]
]
let filteredData = data.filter{
let string = $0["name"] as! String
return string.hasPrefix("Goo")
}
If you want a contains you just need to do a find in the string.
Again, I'm not lying here. I'm running it in a Playground to check...
For a contains search you can do this...
let filteredData = data.filter{
let string = $0["name"] as! String
return string.rangeOfString("db") != nil
}

how manipulate a NSDictionary generated by a json file in swift

I've a NSDictionary populated by a JSON file.
JSON file content (initially)
{
"length" : 0,
"locations" : []
}
I want add some elements in "locations". The elements have the below structure:
[
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
]
In next code I read de JSON File
let contentFile = NSData(contentsOfFile: pathToTheFile)
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: nil, error: &writeError) as NSDictionary`
like you can see jsonDict contain the JSON's info but in a NSDictionary object.
At this point I can't add the elements mentioned before, I tried insert NSData, NSArray, Strings, and nothing results for me
After do this I want convert "final" NSDictionary in JSON again to save it in a file.
The "final" NSDictionary must be like this
{
"length" : 3,
"locations" : [
{
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
},
{
"name" : "some_name_2",
"lat" : "8.88889",
"long" : "9.456789",
"date" : "19/01/2015"
},
{
"name" : "some_name_3",
"lat" : "67.88889",
"long" : "5.456789",
"date" : "19/01/2015"
}
]
}
"length" control the index for new element
I have no more ideas to do this. thanks in advance
If you want to be able to modify the dictionary, you can make it mutable:
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: .MutableContainers, error: &writeError) as NSMutableDictionary
The resulting NSMutableDictionary can be modified. For example:
let originalJSON = "{\"length\" : 0,\"locations\" : []}"
let data = originalJSON.dataUsingEncoding(NSUTF8StringEncoding)
var parseError: NSError?
let locationDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &parseError) as NSMutableDictionary
locationDictionary["length"] = 1 // change the `length` value
let location1 = [ // create dictionary that we'll insert
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
]
if let locations = locationDictionary["locations"] as? NSMutableArray {
locations.addObject(location1) // add the location to the array of locations
}
If you now constructed JSON from the updated locationDictionary, it would look like:
{
"length" : 1,
"locations" : [
{
"long" : "5.456789",
"lat" : "4.88889",
"date" : "19/01/2015",
"name" : "some_name"
}
]
}