Using POST request in HTTP method holds the UI? - ios

When I tap on button it will perform a service request operation.Based on the result it will redirect to next view controller.
After loading Next view controller holds or block the UI. How to solve this issue ? I am using RestAPI and GCD first time in swift, so don't know how to solve this.....
This is login button
#IBAction func btnLogin(_ sender: Any)
{
self.api()
}
This is the function what we call.
func api()
{
let myURL = URL(string: "http://www.digi.com/laravel_api_demo/api/demoapipost")
let request = NSMutableURLRequest(url: myURL!)
request.httpMethod = "POST"
let strEmail = tfLgnID.text
let strPwd = tfPwd.text
let postString = ["username":strEmail, "password":strPwd]
//let postString = ["username":"ayush", "password":"abc"]
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create the session object
//let session = URLSession.shared
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
print("Successfully passed data to server")
} catch let error {
print(error.localizedDescription)
}
let postTask = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("POST Method :\(json)")
let dict = json as? [String: Any]
let num = dict!["status"]
print("Status : \(num)")
print("Dict : \(dict)")
print("username : \(dict!["username"])")
print("password : \(dict!["password"])")
if dict!["status"] as! Int == 1
{
print("Successfully Logged In")
DispatchQueue.main.async {
let visitorVC = self.storyboard?.instantiateViewController(withIdentifier: "VisitorVC") as! VisitorVC
self.present(visitorVC, animated: true, completion: nil)
}
print("OK")
}
else
{
print("Not OK")
}
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
}
postTask.resume()
}

Try this method
func api() {
var request = URLRequest(url: URL(string: "")!) // put your url
request.httpMethod = "POST"
let strEmail = tfLgnID.text
let strPwd = tfPwd.text
let postString:String = "user_id=\(strEmail)&user_id=\(strPwd)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
print(jsonResult)
let status = jsonResult["status"]! as! NSString
print("status\(status)")
DispatchQueue.main.async(execute: {
// your error Alert
})
}
else {
DispatchQueue.main.async(execute: {
let visitorVC = self.storyboard?.instantiateViewController(withIdentifier: "VisitorVC") as! VisitorVC
self.present(visitorVC, animated: true, completion: nil)
})
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
}

Related

How to get JSON response data from shared class to ViewController?

I'm not using Alamofire, so i want to use JSON post approach in SharedClass and i want to send my api name and all parameters to that function. Finally i want to get the response back. I tried but it's not working. If it's not correct please correct me or if any other options are available please suggest me.
My code in SharedClass
func postRequestFunction(apiName:String , parameters:String ) -> [String:Any] {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
print(error!)
// print("error=\(String(describing: error))")
print("localizedDescription : \(String(describing: error?.localizedDescription))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
print(returnRes)
} catch let error as NSError {
print(error)
}
}
task.resume()
return returnRes
}
In my view controller class my code is. Here i'm calling function
func getProjectDetails() {
let response = SharedClass.sharedInstance.postRequestFunction(apiName: "API Name", parameters: parameters)
print(response)
let res = response["Response"] as! [String:Any]
let status = res["status"] as! String
if status == "SUCCESS" {
//I will handle response here
} else {
let message = res["message"] as! String
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: message)
}
}
Here is my solution:
class APIManager {
private init () {}
static let shared = APIManager()
func postRequestFunction(apiName: String , parameters: String, onCompletion: #escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
onCompletion(false, error, nil)
} else {
guard let data = data else {
onCompletion(false, error, nil)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
onCompletion(true, nil, returnRes)
} catch let error as NSError {
onCompletion(false, error, nil)
}
} else {
onCompletion(false, error, nil)
}
}
}
task.resume()
}
}
func getProjectDetails() {
/* Notes:
** onCompletion Block Parameters:
success - This indicates whether the API called successfully or not.
error - This indicates errors from either API calling failed, JSON parsing, or httpStatus is not 200.
result - This indicates the JSON parsed result.
** APIManager:
I have renamed your SharedClass to APIManager for better readibility.
** sharedInstance:
I have renamed sharedInstance to shared for better readibility.
*/
APIManager.shared.postRequestFunction(apiName: "API Name", parameters: "parameters") { (success, error, result) in
if success {
if let res = result?["Response"] as? [String: Any] {
if let status = res["status"] as? String {
if status == "SUCCESS" {
//You can handle response here.
} else {
let message = res["message"] as! String
//Call alert function.
}
}
}
} else {
print(error?.localizedDescription)
}
}
}
You forgot the asynchronous paradigm of Service, You can return your API response in Closure, as like below
func postRequestFunction(apiName:String , parameters:String, returnRes: #escaping ([String: Any]) -> () ) {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {
// check for fundamental networking error
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
if let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] {
returnRes(response)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
}
And use like below
postRequestFunction(apiName: "yourUrl", parameters: "Param") { (response) in
print(response)
}

How to reload new data to UITable when one row data is deleted or updated in swift IOS?

So for I've a UITableView in which I'm showing comments which is fetch from my localhost DB, when a user post comment it's send to localhost and store there and it the same time I reload table and the comment is shown it the time but when a user delete a comment or update a comment then in the DB data is actually deleted or updated but my tableview is not reloading with new data till I close the view and open it again.
following is my code.
This my delete comment code:
#objc func deleteComment(){
ProgressHUD.show("Wait Deleting", interaction: false)
customView.removeFromSuperview()
var commentArray : Dictionary<String, Any> = [:]
commentArray["commentId"] = self.getCommentId
let myUrl = URL(string: "http://127.0.0.1:8000/api/comment/delete");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.addValue("application/json", forHTTPHeaderField: "Content-type")
guard let httpbody = try? JSONSerialization.data(withJSONObject: commentArray, options: []) else { return }
request.httpBody = httpbody
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// print out response object
// print("response = \(response)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if parseJSON["delete"] != nil{
ProgressHUD.dismiss()
self.alertDeleted()
}else {
if parseJSON["error"] != nil{
ProgressHUD.dismiss()
print(parseJSON["error"] as Any)
}
}
}
} catch {
print(error)
}
}
task.resume()
}
This is delete comment alert.
public func alertDeleted(){
let alertController = UIAlertController(title: "Comment Deleted:", message: "Press Ok to continue.", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Ok", style: .default) { (_) in
self.showMatchCommentsApiCall()
}
alertController.addAction(confirmAction)
self.present(alertController, animated: true, completion: nil)
}
This is update comment code.
#objc func updateComment(){
ProgressHUD.show("Wait Upating", interaction: false)
updateCommentView.removeFromSuperview()
var commentArray : Dictionary<String, Any> = [:]
commentArray["commentId"] = self.getCommentId
commentArray["updatedComment"] = textView.text
let myUrl = URL(string: "http://127.0.0.1:8000/api/comment/update");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.addValue("application/json", forHTTPHeaderField: "Content-type")
guard let httpbody = try? JSONSerialization.data(withJSONObject: commentArray, options: []) else { return }
request.httpBody = httpbody
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// print out response object
//print("response = \(response)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if parseJSON["update"] != nil{
ProgressHUD.dismiss()
self.alertCommentUpdated()
self.showMatchCommentsApiCall()
return
}else {
if parseJSON["error"] != nil{
ProgressHUD.dismiss()
print(parseJSON["error"] as Any)
}
}
}
} catch {
print(error)
}
}
task.resume()
}
My ShowMatchCommentsApiCall() function.
public func showMatchCommentsApiCall(){
ProgressHUD.show("Please Wait", interaction: false)
guard let url = URL(string: "http://127.0.0.1:8000/api/matchComments/\(getMatchId)") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
// print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
//print(jsonArray)
for comments in jsonArray{
guard let commentID = comments["commentId"] as? Int else { return }
guard let userID = comments["userId"] as? Int else { return }
guard let userName = comments["userName"] as? String else { return }
let userImgUrl = comments["userImg"] as? String
if userImgUrl != nil{
self.commentsUserImgUrl.append(userImgUrl!)
}else {
self.commentsUserImgUrl.append("nil")
}
guard let commentMessage = comments["comment"] as? String else { return }
self.commentId.append(commentID)
self.commmentsUserId.append(userID)
self.commentsUserName.append(userName)
self.comments.append(commentMessage)
}
} catch let parsingError {
print("Error", parsingError)
}
DispatchQueue.main.async {
self.MatchScoreTable.reloadData()
ProgressHUD.dismiss()
}
}
task.resume()
}
STEP 1. :self.commentsArray.remove(at: indexPath.row)
STEP 2. : self.tableView.deleteRows(at:[indexPath],with:UITableViewRowAnimation.automatic)
STEP 3. : self.tableView.reloadData()
After deleting or updating data just call a UITableView method reloadData
Syntax is as follows :
tableView.reloadData()

URLSession parameters must be valid

This is the Url I am requesting for :
https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq
If you run this on browser, it works fine and gives a JSON response. However I get this error in the catch block on running the following code : URLSession parameters must be valid :
let callURL = URL.init(string: urlString) // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType)
request.httpMethod = HTTPMethod_Get
let dataTask = urlSession.dataTask(with: request) { (data,response,error) in
if error != nil{
completion(nil)
return
}
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
print("Result",resultJson)
if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
print("News",news)
completion(news)
return
}
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
I am not sure what is wrong in your code but I have tested your above code in playground I am getting news below is the code
import Foundation
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let urlString = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq"
let callURL = URL.init(string: urlString) // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.addValue("Content-Type", forHTTPHeaderField: "application/json")
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) { (data,response,error) in
let res = response as! HTTPURLResponse
print(res)
if error != nil{
print(error!)
return
}
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
print("Result",resultJson)
if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
print("News",news)
return
}
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
This worked with me
let callURL = URL.init(string: "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq") // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.httpMethod = HTTPMethod.get.rawValue
let dataTask = URLSession.shared.dataTask(with: request) { (data,response,error) in
if error != nil{
print(error)
}
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
print("Result",resultJson)
if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
print("News",news)
return
}
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
You don't need an URLRequest for a GET request, it's the default, just pass the URL
This works, however there is no value for key articles
let urlString = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq"
let callURL = URL(string: urlString)!
let dataTask = URLSession.shared.dataTask(with: callURL) { (data,response,error) in
if error != nil { return }
do {
if let resultJson = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
print("Result",resultJson)
// if let news = resultJson["articles"] as? [[String:Any]] {
// print("News",news.count)
// return
// }
}
} catch {
print("Error -> \(error)")
}
}
dataTask.resume()
And – as always – do not use NSDictionary and valueForKey in Swift and .allowFragments is pointless if the root object is a collection type.

How to send form data in POST request in Swift 3

I am trying to post form-data using webservice, userName & password, but in response it's showing an error stating "Could not connect to the server.".
Please help me to send form data in the POST request.
let dict:[String:String] = ["userName": userName as! String, "password": password as! String]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let url = URL(string: "(some url)")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue:String = parseJSON["success"] as! String;
print("result: \(resultValue)")
print(parseJSON)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
} catch {
print(error.localizedDescription)
}
I've tried adding values in the request, may be some values are missing in the request formed. Please help!
Thats the POSTMAN response
my calling api class
class ApiService
{
static func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
static func callPost(url:URL, params:[String:Any], finish: #escaping ((message:String, data:Data?)) -> Void)
{
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = self.getPostString(params: params)
request.httpBody = postString.data(using: .utf8)
var result:(message:String, data:Data?) = (message: "Fail", data: nil)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if(error != nil)
{
result.message = "Fail Error not null : \(error.debugDescription)"
}
else
{
result.message = "Success"
result.data = data
}
finish(result)
}
task.resume()
}
}
and when use it
ApiService.callPost(url: url, params: params, finish: finishPost)
and the finish function
func finishPost (message:String, data:Data?) -> Void
{
do
{
if let jsonData = data
{
let parsedData = try JSONDecoder().decode(Response.self, from: jsonData)
print(parsedData)
}
}
catch
{
print("Parse Error: \(error)")
}
}

Parse JSON response with Swift 3

I have JSON looking like this:
{"posts":
[
{
"id":"1","title":"title 1"
},
{
"id":"2","title":"title 2"
},
{
"id":"3","title":"title 3"
},
{
"id":"4","title":"title 4"
},
{
"id":"5","title":"title 5"
}
],
"text":"Some text",
"result":1
}
How can I parse that JSON with Swift 3?
I have this:
let url = URL(string: "http://domain.com/file.php")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
// Parse JSON
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
}
Use this to parse your data:
let url = URL(string: "http://example.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let posts = json["posts"] as? [[String: Any]] ?? []
print(posts)
} catch let error as NSError {
print(error)
}
}).resume()
Use guard to check if you have data and that error is empty.
Swift 5.x version
let url = URL(string: "http://example.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
let posts = json?["posts"] as? [[String: Any]] ?? []
print(posts)
} catch {
print(error)
}
}).resume()
In swift 3.0 for GET method:
var request = URLRequest(url: URL(string: "Your URL")!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
In swift 3.0 for POST method:
var request = URLRequest(url: URL(string: "Your URL")!)
request.httpMethod = "POST"
let postString = "user_name=ABC" // Your parameter
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
Because your data structure of test json should be "[String: AnyObject]". The json key "posts" value is Array type.
DISTANCE--DIFFICULT API
========================>
class ViewController: UIViewController {
var get_data = NSMutableData()
var get_dest = NSArray()
var org_add = NSArray()
var row_arr = NSArray()
var ele_arr = NSArray()
var ele_dic = NSDictionary()
var dist_dic = NSDictionary()
var dur_dic = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getmethod()
}
func getmethod()
{
let url_str = URL(string: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&departure_time=1408046331&origins=37.407585,-122.145287&destinations=37.482890,-122.150235")
let url_req = URLRequest(url: url_str!)
let task = URLSession.shared.dataTask(with: url_req) { (data, response, error) in
if let my_data = data
{
print("my data is----->",my_data)
do
{
self.get_data.append(my_data)
let jsondata = try JSONSerialization.jsonObject(with: self.get_data as Data, options: [])as! NSDictionary
print("json data is--->",jsondata)
self.get_dest = jsondata.object(forKey: "destination_addresses")as! NSArray
let get_dest1:String = self.get_dest.object(at: 0) as! String
print("destination is--->",get_dest1)
self.org_add = jsondata.object(forKey: "origin_addresses")as! NSArray
let get_org:String = self.org_add.object(at: 0)as! String
print("original address is--->",get_org)
self.row_arr = jsondata.object(forKey: "rows")as! NSArray
let row_dic = self.row_arr.object(at: 0)as! NSDictionary
self.ele_arr = row_dic.object(forKey: "elements")as! NSArray
self.ele_dic = self.ele_arr.object(at: 0)as! NSDictionary
self.dist_dic = self.ele_dic.value(forKey: "distance")as! NSDictionary
print("distance text is--->",self.dist_dic.object(forKey: "text")as! String)
print("distance value is--->",self.dist_dic.object(forKey: "value")as! Int)
// self.ele_dic = self.ele_arr.object(at: 1)as! NSDictionary
self.dur_dic = self.ele_dic.value(forKey: "duration")as! NSDictionary
print("duration text--->",self.dur_dic.value(forKey: "text")as! String)
print("duration value--->",self.dur_dic.value(forKey: "value")as! Int)
print("status---->",self.ele_dic.object(forKey: "status")as! String)
}
catch
{
print("error is--->",error.localizedDescription)
}
}
};task.resume()
}

Resources