Get value from server reponse swift - ios

I am new to Swift,
I want to get value of latitude and longitde from server reponse.
How do i get the value?
Here is my code:
WebServiceHelper.sharedInstance.makeWebServiceCall(urlAddress: "http://jsonplaceholder.typicode.com/users/1", requestMethod: "GET", params: ["Key" : "value"], Success: { (JSON:Any) in
print("Success Received data is: \(JSON)")
}, Error: { (JSON:Any) in
print("Error Received data is: \(JSON)")
}) { (JSON:Any) in
print("Header Received data is: \(JSON)")
}
I am able to get server reponse Here it is:
Success Received data is: {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"latitude": "-37.3159",
"longitude": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
How do i get?

you can try like this to get lat long :
if let result = JSON as? [String:AnyObject]{
let address = result?["address"] as? [String:AnyObject]
let geo = address?["geo"] as? [String:AnyObject]
print(geo?["lng"])
print(geo?["lat"]) }

Related

assigning "Get" Request data to Text field

My get data response is like
I want "title" and "date" should be shown in my view controller "label values"
get method calls when app running and the data should display in either text fields "or" in label
My Code is
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError() }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
out put is :
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
]
I want to print "username":
"email":
values in my Storyboard labels
The result contains multiple users, so you should first iterate over them and find the user you want. Then you can set text on your UI elements in the Main thread.
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError() }
typealias User = [String: Any]
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let usersJson = try JSONSerialization.jsonObject(with: data, options: []) as! [User]
print(usersJson)
// Since the result is an array of users
for user in usersJson {
guard let userName = user["username"] as? String else { return assertionFailure("Invalid username") }
print(userName)
// All UI works should done in main thread
DispatchQueue.main.async {
<#usernameLabel#>.text = username
}
}
} catch {
print(error)
}
}
}.resume()
I suggest you take a look at Swift Codable. It will boost your coding and minimize syntax and human errors.

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()
}

Send multiple array in parameter in swift

I'm calling a service in which I'm trying to send parameter that consist of array within an array and other parameters which are outside from an array. The format in which I have to send parameter is this:
{
"RestID": 0,
"cart": [
{
"childs": [
{
"addon_cat_id": 0,
"id": 0,
"name": "string",
"next_move_id": 0,
"price": 0,
"sort_order": 0,
"type": "string"
}
],
"name": "string",
"price": "string",
"productid": 0,
"qty": 0,
"description": "string"
}
],
"coupon_code": "string",
"coupon_type": "string",
"coupon_value": 0,
"delivery_price": "string",
"discount_amount": "string"
}
This is how I'm sending my parameter in the service:
let parameter:[String:Any] = ["RestID":restaurantId!,
"cart":[["childs":["addon_cat_id":"0",
"id":ItemDataSource.sharedInstance.items[0].itemId!,
"name":ItemDataSource.sharedInstance.items[0].itemName!,
"next_move_id":"",
"price":ItemDataSource.sharedInstance.items[0].itemPrice!,
"sort_order":"",
"type":"string"
]],
["name": ItemDataSource.sharedInstance.items[0].itemName!,
"price": ItemDataSource.sharedInstance.items[0].itemPrice!,
"productid": ItemDataSource.sharedInstance.items[0].itemId!,
"qty": 2,
"description":ItemDataSource.sharedInstance.items[0].itemDdescription!]
],
"coupon_code" : couponCode!,
"coupon_type" : couponType!,
"coupon_value" : couponValue!,
"delivery_price" : deliveryLbl.text!,
"discount_amount" : disocunt!,
"discount_description" : discountDesc!,
"discount_info" : discountInfo!,
"distance": "",
"door_num" : doorTxt.text!,
"firstname" : "",
"lastname" : "",
"order_type" : "Delivery",
"payment_mode" : "",
"phone" : mobileTxt.text!,
"postcode" : postCodeTxt.text!,
"preorder" : true,
"preorder_is_preorder" : "",
"street" : address1Txt.text!,
"token" : "",
"town" : addressTxt2.text!,
"total": self.grandTotalLbl.text!,
"stripeToken" : "",
"customer_id" : "2",
"preordertime": preOrderTime,
"usercmt": "descri",
"email": userEmail!
]
But when I call the service I get an error. I have discussed this with the server side and they are saying it is a mistake in sending the parameter. How can I send multiple arrays within an array in parameter?
This is my service class:
class SaveOrderDeliveryService{
static let instance = SaveOrderDeliveryService()
var status:Int = 0
func saveOrderDelivery(param:[String:Any],completion:#escaping CompletionHandler) {
Alamofire.request(saveOrderDeliveryUrl, method: .post, parameters:param, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)")// response serialization result
print(response)
if response.result.error == nil{
self.status = (response.response?.statusCode)!
if(self.status == 200){
print(response)
guard let data = response.data else {return}
do{
if let json = try JSON(data: data).dictionary{
completion(true)
}
}catch let jsonErr{
print(jsonErr)
}
}
completion(true)
}else{
completion(false)
debugPrint(response.result.error as Any)
}
}
}
}
Try this add your data , make sure now one with nil
let parameters = [
"RestID": "",
"cart": [
[
"childs": [
[
"addon_cat_id": "",
"id": "",
"name": "string",
"next_move_id": "",
"price": "",
"sort_order": "",
"type": "string"
]
],
"name": "string",
"price": "string",
"productid": "",
"qty": "",
"description": "string"
]
],
"coupon_code": "string",
"coupon_type": "string",
"coupon_value": "",
"delivery_price": "string",
"discount_amount": "string"
] as [String : Any]
Alamofire.request(saveOrderDeliveryUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
}

How to display NsMutable Array

When decoding JSON response from webservice I get an ouput saying:
["dataresult": <__NSArrayM 0x1c0243090>( )]
How to display / decode this NSArrayM
Any help on this would be appreciated
Below is the code
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print("JSON yet to be parsed")
if let parseJSON = json {
let myBoard = parseJSON["message"] as! [String:Any]
print("JSON parsed successfully !")
print(myBoard)
if let refResults = myBoard["dataresult"] as? [[String:String]]{
let valueArray = refResults.map {$0["Success"]!}
self.Contact = valueArray
print(self.Contact)
}
Response from the Web Service:
"message": {
"dataresult": [
{
"Success": "Success",
"OwnerName": "test shop",
"mobileno": "1231231231",
"landline": "",
"managername": "acsd acfacaf",
"managerContact": "",
"email": "test#gmail.com",
"website": "",
"address": "gggysgyysusisss",
"city": "hgyggg",
"area": "fgatsbsuhsushsu",
"pincode": "123123",
"rentowned": "Leased",
"homedelivary": "Yes",
"working_start_time": "10.00 am",
"working_end_time": "7.30 pm",
"pwd": "123123"

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