Swift - Parse certain data - ios

Need to extract the data of desc from the below API response. From that i need to extract every a and b, so that i can use that in for a math addition app.
data from the server
[
{
"id": 226,
"name": "chorename",
"desc": "{\n \"questions\" : [\n {\n \"b\" : 2,\n \"a\" : 1\n },\n {\n \"b\" : 3,\n \"a\" : 2\n },\n {\n \"b\" : 2,\n \"a\" : 8\n },\n {\n \"b\" : 9,\n \"a\" : 7\n },\n {\n \"b\" : 3,\n \"a\" : 6\n }\n ],\n \"operation\" : \"addition\"\n}",
"reward": "1.00",
"sched": "2018-04-19T15:54:24.657644+08:00",
"parent": "shit",
"type": "homework",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "ongoing"
},
"date_created": "2018-04-23T14:16:35.739436+08:00",
"date_modified": "2018-04-23T14:16:35.790237+08:00"
}
]
code on getting request
func demoApi1() {
Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Ang Response: , \(json)")
for item in json {
var a = self.getAllDetail.append(item )
print("shit:" , a)
// if let title = item["title"] as? String {
// self.titleArray.append(title)
// }
}
if !self.getAllDetail.isEmpty{
DispatchQueue.main.async {
}
}
break
case .failure(_):
print("Error")
break
}
}
}
let devices = assign "a" here
let randomIndex = Int(arc4random_uniform(UInt32(devices.count)))
let randomItem = devices[randomIndex]
print("random item:" ,randomItem)
let device2 = //assign "b" here
let randomIndex1 = Int(arc4random_uniform(UInt32(devices.count)))
let randomItem1 = device2[randomIndex]
API Response:
Ang Response [["status": {
name = ongoing;
}, "sched": 2018-04-10T14:22:00+08:00, "desc": asdasdasdsa, "id": 224, "reward": 1.00, "parent": das, "child": dasdas, "date_created": 2018-04-19T15:54:24.657644+08:00, "name": sad, "occurrence": {
name = once;
}, "type": , "date_modified": 2018-04-19T15:54:24.703520+08:00], ["status": {
name = ongoing;
}, "sched": 2018-04-19T15:54:24.657644+08:00, "desc": {
"questions" : [
{
"b" : 2,
"a" : 1
},
{
"b" : 3,
"a" : 2
},
{
"b" : 2,
"a" : 8
},
{
"b" : 9,
"a" : 7
},
{
"b" : 3,
"a" : 6
}
],
"operation" : "addition"
}, "id": 226, "reward": 1.00, "parent": shit, "child": , "date_created": 2018-04-23T14:16:35.739436+08:00, "name": chorename, "occurrence": {
name = once;
}, "type": homework, "date_modified": 2018-04-23T14:16:35.790237+08:00]]

The below code can be used to convert a json string from string to dictionary
Objective-c
+ (NSDictionary *)dictionaryFromJSONString:(NSString *)jsonString
{
// #"{\"2\":\"3\"}"
NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
return json;
}
SWIFT
func getDictionaryFromString(_ jsonString: String) -> [String:Any]? {
let objectData = jsonString.data(using: .utf8)
var dict: [String:Any]?
if objectData != nil {
do {
dict = try JSONSerialization.jsonObject(with: objectData!, options: .allowFragments) as? [String : Any]
} catch {
print("Error occured.")
}
}
return dict
}
Once the dictionary is created you can use access the value via the key.

Related

Parse JsonArray response data

I have an json array respone like this;
[
{
"id": 62,
"type_id": 1,
"coordinate": {
"x": 2273.73828125,
"y": 1568.015625000001
},
"name": "x"
},
{
"id": 57,
"type_id": 1,
"coordinate": {
"x": 1405,
"y": 343.99999999999704
},
"name": "y"
}
]
I use alomifere 5.2 to get response. How can I parse this data to get all values?
Alamofire.request("YOUR_URL", method:.post, parameters:params, encoding:URLEncoding.default, headers: nil).responseJSON { response in
switch(response.result)
{
case .success(_):
if response.result.value != nil
{
let arr :[[String:Any]] = response.result.value! as! [[String:Any]]
print(arr)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Change successResponse as! [[string:Any]] (array of dictionary)

Getting json response but not able to parse in to label

I am getting response in json format and i have array in to array but I am not able to under stood how to print on label i saw my code here
I am getting response of business_time array value so can any one please help
func CallAPI() {
let preferences = UserDefaults.standard
let uid = "u_id"
let acctkn = "acc_tkn"
if preferences.object(forKey: uid) == nil {
// Doesn't exist
} else {
let u_id = preferences.object(forKey: uid) as! String
print(u_id)
let acc_tkn = preferences.object(forKey: acctkn) as! String
print(acc_tkn)
let userprofile = ["user_id":u_id,"access_token":acc_tkn]
SVProgressHUD.show(withStatus: "Loading...")
Alamofire.request(businessDetailByUserId, method: .post, parameters: userprofile).responseJSON
{
response in
//printing response
print(response)
let result = response.result.value
// let obj=result
if result != nil{
let data = result as! [String : AnyObject]
let userdata = data["data"] as! NSDictionary
let userTimings = userdata["business_time"]
print(userTimings)
SVProgressHUD.dismiss()
}
}
}
}
and here is my response::
{
"success": "1",
"data": {
"bus_usr_id": "12",
"fk_user_id": "88",
"fk_cate_id": "2",
"bus_name": "AutoMobiles",
"bus_logo": "https://www.kwikmypay.com/mode_share/modeshare_admin/assets/images/business/bus_uvbdt1531395509.png",
"bus_address": "404 Palladium",
"bus_email": "mihir#hemshub.com",
"bus_website": "www.hemshub.com",
"bus_desc": "All types of automobiles spare parts are available.",
"fav_status": 1,
"bus_contact_no": "9876543210",
"bus_status": "1",
"sub_cate_list": "Spare Parts",
"category": "Automobiles",
"business_time": [
{
"tbl_bus_time_id": "107",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Monday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "108",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Tuesday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "109",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Wednesday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "110",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Thursday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "111",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Friday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "112",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Saturday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "113",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Sunday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
}
]
},
"message": ""
i want to print values of business_time array on label but i am new to swift so can any one please tell me how to print
if let jsonData = response.result.value as? [String : Any],
let userdata = jsonData["data"] as? [String: Any]
let businessJsonArray = userdata["business_time"] as? [[String: Any]] {
for businessJson in businessJsonArray {
let id = businessJson["tbl_bus_time_id"]
}
}
SVProgressHUD.dismiss()
Above pattern is old. Apple release JsonEndcoder() in swift 4 which you should try.
As you mentioned the value for key business_time is an array so you get multiple items.
Basically don't use NSDictionary and NSArray in Swift, you throw away the important type information and a JSON dictionary in Swift 3+ is always [String:Any], never [String:AnyObject]
//printing response
print(response)
//don't check for `nil`, use optional bindings for all objects
if let result = response.result.value as? [String : Any],
let userdata = result["data"] as? [String : Any],
let userTimings = userdata["business_time"] as? [[String : Any]] {
for timing in userTimings {
print(timing["start_time"] as! String)
print(timing["end_time"] as! String)
}
}
SVProgressHUD.dismiss()
As you can see in each JSON there is response sector responsible for server status (200 = success etc).
Next part is data... so basically, you have several important dictionaries (header, data). To output data without alamofire:
Write to me the response.
func CallAPI()
{
let url = URL(string: "https:// your_Address")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let _ = response, let data = data
{
let result = String(data: data, encoding: .utf8)!
print(result as NSString)
} else {
print(error as Any)
}
}
task.resume()
}

swift parsing desc and parsing selected element

Swift parsing desc and parsing selected element. I want to parse desc and after parsing desc parse desc content. thanks swift parsing desc and parsing selected element.
I have tried different methods. Does anyone have an idea on how we can make it possible? I tried the following code:
**Code for getting the data**
func demoApi1() {
Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Ang Response: , \(json)")
for item in json {
self.getAllDetail.append(item )
if let desc = item["dec"] as? String {
self.titleArray.append(desc)
print("motherfucker:" , self.titleArray)
}
}
if !self.getAllDetail.isEmpty{
DispatchQueue.main.async {
}
}
break
case .failure(_):
print("Error")
break
}
}
}
Response:
Ang Response [["status": {
name = ongoing;
}, "sched": 2018-04-10T14:22:00+08:00, "desc": asdasdasdsa, "id": 224, "reward": 1.00, "parent": das, "child": dasdas, "date_created": 2018-04-19T15:54:24.657644+08:00, "name": sad, "occurrence": {
name = once;
}, "type": , "date_modified": 2018-04-19T15:54:24.703520+08:00], ["status": {
name = ongoing;
}, "sched": 2018-04-19T15:54:24.657644+08:00, "desc": {
"questions" : [
{
"b" : 2,
"a" : 1
},
{
"b" : 3,
"a" : 2
},
{
"b" : 2,
"a" : 8
},
{
"b" : 9,
"a" : 7
},
{
"b" : 3,
"a" : 6
}
],
"operation" : "addition"
}, "id": 226, "reward": 1.00, "parent": shit, "child": , "date_created": 2018-04-23T14:16:35.739436+08:00, "name": chorename, "occurrence": {
name = once;
}, "type": homework, "date_modified": 2018-04-23T14:16:35.790237+08:00]]
String to Dictionary:
func stringToDictionary(_ strToJSON : String)-> [String:Any]{
print("JsonString:\(strToJSON)")
let data = strToJSON.data(using: .utf8)
var dict = [String:Any]()
do {
dict = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
return dict
}
catch let error as NSError {
print("Error is:\(error)")
}
return dict
}
Use it like this:
let dictConv = stringToDictionary("your_string")
print(dictConv)

Extract data from GeoJSON

I am trying to retrieve the featureclass inside the GeoJSON below.
I have updated the GeoJSON below.
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"scalerank": 8,
"name": "Grill",
"website": "www.rocargo.com/SanNicolas.html",
"natlscale": 5,
"featureclass": "Meat"
},
"geometry": {
"type": "Point",
"coordinates": [-11.1086263, 59.1438153]
}
},
{
"type": "Feature",
"properties": {
"scalerank": 8,
"name": "Queen Vic",
"website": "www.rocargo.com/SanNicolas.html",
"natlscale": 5,
"featureclass": "Fish"
},
"geometry": {
"type": "Point",
"coordinates": [-11.1190539, 59.1498404]
}
},
{
"type": "Feature",
"properties": {
"scalerank": 8,
"name": "Josephines",
"website": "www.rocargo.com/SanNicolas.html",
"natlscale": 5,
"featureclass": "Bar"
},
"geometry": {
"type": "Point",
"coordinates": [-11.1145087,59.142496]
}
},
{
"type": "Feature",
"properties": {
"scalerank": 8,
"name": "Fall",
"website": "www.rocargo.com/SanNicolas.html",
"natlscale": 5,
"featureclass": "Port"
},
"geometry": {
"type": "Point",
"coordinates": [-11.1174109, 59.1402164]
}
}
]
}
The below function can pull all the information above.
func pleaseWork() {
let urlBar = Bundle.main.path(forResource: "bars", ofType: "geojson")!
if let jsonData = NSData(contentsOfFile: urlBar) {
do {
if let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
if let responseA : NSArray = jsonResult["features"] as? NSArray {
print(responseA)
}
}
}
catch { print("Error while parsing: \(error)") }
}
I can pull all the information however, I am struggling to get the 'featureclass' information. What steps am I missing?
Thanks.
asdfadsfadsfdsafdsafdsfadsfdsafdsafdasf asdfasdfadsfdsa
I recommend to use Decodable in Swift 4. It's very simple and convenient
Create the structs
struct Collection : Decodable {
let type : String
let features : [Feature]
}
struct Feature : Decodable {
let type : String
let properties : Properties
// there is also geometry
}
struct Properties : Decodable {
let scalerank : Int
let name : String
let website : URL
let natlscale : Int
let featureclass : String
}
Decode the data and print the values for name and featureclass
let urlBar = Bundle.main.url(forResource: "bars", withExtension: "geojson")!
do {
let jsonData = try Data(contentsOf: urlBar)
let result = try JSONDecoder().decode(Collection.self, from: jsonData)
for feature in result.features {
print("name", feature.properties.name, "featureclass", feature.properties.featureclass)
}
} catch { print("Error while parsing: \(error)") }
Step by Step only, you can achieve that.
if let responseA : NSArray = jsonResult["features"] as? NSArray {
for dictVal in 0..<responseA.count
{
let featuresDict = responseA[dictVal] as! NSDictionary
let propertiesDict = featuresDict.value(forKey: "properties") as! NSDictionary
let featureClassName = propertiesDict.value(forKey: "featureclass") as! String
print(featureClassName)
}
}
Try to use this link for Complex JSON validation. You will get clarity.

Swift IOS Reading JSON from url

On the below method, I can get the place value but not the location value. how can I get the location?
Thank you in advance!!
func searchDB(looking: String){
var urlString:String = "URLGOESHERE?q=\(looking)"
let url = NSURL(string: urlString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error)
}
else {
//processing data
if let arr = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [AnyObject] {
for currPlace in arr {
println(currPlace["name"])
println(currPlace["location"])
}
}
else {
errorOccurred = true
}
}//eo potential data
})
task.resume()
}//eom
This is the result output I am getting:
Optional(Buddha-Bar)
Optional(nil)
JSON sample:
sample data:
{
"formatted_address": "8-12 Rue Boissy d'Anglas, 75008 Paris, France",
"geometry": {
"location": {
"lat": 48.868194,
"lng": 2.321596
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id": "560dd225114fd10997f75ee777bad84bcb40c529",
"name": "Buddha-Bar",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 848,
"html_attributions": [],
"photo_reference": "CnRnAAAAifUh9MiqwAgQYdwEp-EnS4e_nPQN_mPYIqdI49UKun_CZKxgtUh_ZqT8QBEqBuel9seoZvyyIVvA5-TlweEqO9_2tORg_cmTi_Cy5L_PAthdZd1_Krqbf7oJNy81RWD3brA8fzeIKJfQTMgo-AT19RIQAg5kKSqeoeedm69uhUWKvBoULDJ1-PoSgv4Lsg5y1rjU_pHm_Ng",
"width": 1919
}
],
"place_id": "ChIJRS81ac1v5kcRRUqQBmTTJJU",
"price_level": 3,
"rating": 3.7,
"reference": "CmReAAAAjJskNN69nw3gBVtqLpsX11Psr-QvK6cHPLhF-oDXAbYq7dwLn65b1svUJOLVnRgAbg4K3w7qCj9_hkXvx20q4YNR2714ZQQw89GyFGCtXAxonRh09_uvgK97DewsYRyUEhAczR_GzOvU0mmG1OZr0X3kGhQeJ1Vr3RSnI6VXyzh83W_LIcUK_g",
"types": [
"bar",
"restaurant",
"food",
"establishment"
]
},
Json data without spaces
sample data:
{
"formatted_address": "8-12 Rue Boissy d'Anglas, 75008 Paris, France",
"geometry": {
"location": {
"lat": 48.868194,
"lng": 2.321596
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id": "560dd225114fd10997f75ee777bad84bcb40c529",
"name": "Buddha-Bar",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 848,
"html_attributions": [],
"photo_reference": "CnRnAAAAifUh9MiqwAgQYdwEp-EnS4e_nPQN_mPYIqdI49UKun_CZKxgtUh_ZqT8QBEqBuel9seoZvyyIVvA5-TlweEqO9_2tORg_cmTi_Cy5L_PAthdZd1_Krqbf7oJNy81RWD3brA8fzeIKJfQTMgo-AT19RIQAg5kKSqeoeedm69uhUWKvBoULDJ1-PoSgv4Lsg5y1rjU_pHm_Ng",
"width": 1919
}
],
"place_id": "ChIJRS81ac1v5kcRRUqQBmTTJJU",
"price_level": 3,
"rating": 3.7,
"reference": "CmReAAAAjJskNN69nw3gBVtqLpsX11Psr-QvK6cHPLhF-oDXAbYq7dwLn65b1svUJOLVnRgAbg4K3w7qCj9_hkXvx20q4YNR2714ZQQw89GyFGCtXAxonRh09_uvgK97DewsYRyUEhAczR_GzOvU0mmG1OZr0X3kGhQeJ1Vr3RSnI6VXyzh83W_LIcUK_g",
"types": [
"bar",
"restaurant",
"food",
"establishment"
]
},
Adding a little formatting to the pertinent part of the data:
sample data: {
"formatted_address": "8-12 Rue Boissy d'Anglas, 75008 Paris, France",
"geometry": {
"location": {
"lat": 48.868194,
"lng": 2.321596
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id": "560dd225114fd10997f75ee777bad84bcb40c529",
"name": "Buddha-Bar",
It is unclear what "sample data:" means as it is not quoted, it may be something added by the print statement (my guess) in which case it is not needed to access the components.
The name would be addresses as:
["name"]
The location is in lat/lon so there will be two accesses:
["geometry"]["location"]["lat"]
["geometry"]["location"]["lon"]
In the above the applicable language syntax must be applied, in Swift there will be some pain.
See json.org for information on JSON.
After some frustration and game of thrones. the messy solution was the one below.
an alternative may be api like
https://github.com/lingoer/SwiftyJSON
func searchDB(looking: String){
var errorOccurred:Bool = false
var urlString:String = "URLGOESHERE?q=\(looking)"
let url = NSURL(string: urlString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error)
errorOccurred = true
} else {
// println(response) //response from post
//processing data
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let statusesArray = jsonObject as? NSArray{
println("********* LEVEL 1 *******")
println(statusesArray[0])
if let aStatus = statusesArray[0] as? NSDictionary{
println("********* LEVEL 2 *******")
println(aStatus)
if let geometry = aStatus["geometry"] as? NSDictionary{
println("********* LEVEL 3 *******")
println(geometry)
if let currLocation = geometry["location"] as? NSDictionary{
println("********* LEVEL 4 *******")
println(currLocation)
println(currLocation["lat"])
println(currLocation["lng"])
}
}
}
}
else {
errorOccurred = true
}
}//eo potential data
})
task.resume()
}//eom

Resources