how to post base64encoded image to server using swift 3? - ios

Here I have to post base64encoded image to server. Below is my code which I am using:
func post_request_image(api:String){
if (imageview.image == nil)
{
return
}
let image_data = UIImageJPEGRepresentation(imageview.image!, 1.0)
if(image_data == nil)
{
return
}
loader.showLoadingAlert(view: self.view, title: "")
var web_apis_3 = api
// print(web_apis_3)
var request = URLRequest(url: URL(string: web_apis_3)!)
request.httpMethod = "POST"
do {
request.httpBody =
image_data?.base64EncodedString()
} catch let error {
print(error.localizedDescription)
}
// let content = String(data: json!, encoding:
String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(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 = \(response)")
}
}
But it is giving me this error:
cannot assign value of type String to type Data
How can I resolve this?

if the server expects a string:
let image = UIImage(named: "sample")
guard let imgData = UIImagePNGRepresentation(image) else { return }
let base64String = imgData.base64EncodedString(options: .lineLength64Characters)
then submit base64String to the server in whatever way is needed.
for me I needed to submit:
let parameters: [String: String] = [
"image": base64String
]
since youre needing data, you should be able to submit imgData

Related

How to Pass Key Value Parameter in JSON POST method in Swift?

This is API http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/
its parameter: "contactsList" : ["5987606147", "6179987671", "5082508888"]
its header: ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
In my code if i put breakpoint then filtertaggedUser() is calling but i am unable to go inside completionHandler the access is not going inside dataTask
Access going to else part why? the api is working.
i am trying to pass parameter key value in URL string like below
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
is this correct approch?
code for above API:
func filtertaggedUser() {
print("inside filter taggedusers")
let headers = ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
// access not coming here
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
print("filter taggedusers inside")
do {
print("filter taggedusers inside do")
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
print("filter taggedusers \(jsonObject)")
} catch { print(error.localizedDescription) }
} else { Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self) }
})
dataTask.resume()
}
OUTPUT:
POSTMAN OUTPUT
POSTMAN Body
why response is not coming, where i did mistake, please help me with the code.
We can call the Post request API like below,
func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
print(data.map { String($0) }.joined(separator: "&"))
return data.map { String($0) }.joined(separator: "&")
}
func callPostApi(){
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
request.setValue("584D97F-761A-4C24-8C4B-C145A8B8BD75", forHTTPHeaderField: "deviceid")
request.setValue("9609cc826b0d472faf9967370c095c21", forHTTPHeaderField: "key")
request.setValue("personal", forHTTPHeaderField: "userType")
let parameters = getPostString(params: ["contactsList":["8908908900"]])
request.httpBody = parameters.data(using: .utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
print(httpResponse!.statusCode)
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}
Output :
{"8908908900":{"userId":"9609cc826b0d472faf9967370c095c21","userName":"Satish Madhavarapu","profilePic":null,"oniTaag":true,"tagged":false,"userType":"personal"}}

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

swiftyJson returns null in nested json

I'm using this function to send post values to server:
func getFirstPageApplication(EMPTY:String,completionHandler: #escaping (_ response: String) -> ())
{
var strResponse = "null"
var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
request.httpMethod = "POST"
let postString = "EMAIL=\(EMPTY)"
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=\(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 = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
strResponse = responseString!
completionHandler(strResponse)
}
task.resume()
}
in my other controller I use this function to use above method:
func initialFirstView()
{
RestApiManager.sharedInstance.getFirstPageApplication(EMPTY:"-"){
response in
let json = JSON(response)
print("res: \(json["sliders"])")
}
}
I got response value but json["sliders"] returns null, I don't know!
my response value:
{"sliders":[{"id":4,"title":"\u0647\u0645\u06cc\u0634\u0647 \u0628\u0647 \u0622\u0648\u0627\u0632 \u0628\u0627 \u0627\u0633\u062a\u0627\u062f\u06a9\u062a","image":"1500801181_ostadcat_slider_1.jpg","status":1,"created_at":"2017-07-23 04:43:01","updated_at":"2017-07-23 04:43:01"},{"id":6,"title":"\u06cc\u06a9\u06cc \u0628\u0631\u0627\u06cc \u0647\u0645\u0647, \u0647\u0645\u0647 \u0628\u0631\u0627\u06cc \u06cc\u06a9\u06cc","image":"1500801699_ostadcat_slider_3.jpg","status":1,"created_at":"2017-07-23 04:51:39","updated_at":"2017-07-23 04:51:39"},{"id":7,"title":"\u062d\u0631\u0641\u0647 \u0627\u06cc \u062a\u0631\u06cc\u0646 \u0627\u067e\u0644\u06cc\u06a9\u06cc\u0634\u0646 \u0645\u0648\u0633\u06cc\u0642\u06cc","image":"1500801728_ostadcat_slider_4.jpg","status":1,"created_at":"2017-07-23 04:52:08","updated_at":"2017-07-23 04:52:08"},{"id":8,"title":"\u062a\u0648 \u0647\u0645 \u0645\u06cc \u062a\u0648\u0646\u06cc \u0645\u062b\u0644 \u0645\u0646 \u0628\u0627\u0634\u06cc!!!","image":"1500801751_ostadcat_slider_2.jpg","status":1,"created_at":"2017-07-23 04:52:31","updated_at":"2017-07-23 04:52:31"}],"tutorials":[{"id":1,"home_image":"1500806287_img_home_test_6.png","tutorial_image":"1500809220_Hot-Romanian-Inna-in-black-goggles-wallpapers.jpg","tutorial_title":"\u062e\u0648\u0627\u0646\u0646\u062f\u06af\u06cc","tutorial_description":"\u0622\u0645\u0648\u0632\u0634 \u062c\u0627\u0645\u0639 \u062e\u0648\u0627\u0646\u0646\u062f\u06af\u06cc","video":"1500810916_innaHot2.mp4","video_title":"\u062e\u0648\u0627\u0646\u0646\u062f\u06af\u06cc \u0631\u0627 \u062d\u0631\u0641\u0647 \u0627\u06cc \u06cc\u0627\u062f \u0628\u06af\u06cc\u0631\u06cc\u062f","teacher_image":"1500808975_inna-dark-hair-white-dresses-digital-art.jpg","teacher_name":"\u0627\u06cc\u0646\u0627","teacher_bio":"\u0628\u0647\u062a\u0631\u06cc\u0646 \u0627\u0632 \u0633\u0627\u0644 2009 \u062a\u0627 \u0628\u0647 \u0627\u0644\u0627\u0646","status":1,"created_at":"2017-06-29 17:31:20","updated_at":"2017-07-23 11:55:16"},{"id":2,"home_image":"1500802877_img_home_test_1.jpg","tutorial_image":"1500802877_Image.png","tutorial_title":"\u0622\u0645\u0648\u0632\u0634 \u06af\u06cc\u062a\u0627\u0631 \u0627\u0633\u0644\u0634","tutorial_description":"\u06af\u06cc\u062a\u0627\u0631 \u0627\u0633\u0644\u0634 \u0631\u0627 \u06cc\u0627\u062f \u0628\u06af\u06cc\u0631\u06cc\u062f!!!","video":"1500804433_oneRepublic.mp4","video_title":"\u0646\u0645\u0648\u0646\u0647 \u0622\u0645\u0648\u0632\u0634 \u06af\u06cc\u062a\u0627\u0631","teacher_image":"1500802882_maxresdefault.jpg","teacher_name":"\u0648\u0627\u0646 \u0631\u06cc\u067e\u0627\u0628\u0644\u06cc\u06a9","teacher_bio":"\u06af\u0631\u0648\u0647 \u0648\u0627\u0646 \u0631\u06cc\u067e\u0627\u0628\u0644\u06cc\u06a9 \u0634\u0627\u0645\u0644 5 \u0639\u0636\u0648","status":1,"created_at":"2017-06-29 17:35:09","updated_at":"2017-07-23 05:37:13"}]}
#Reinier Melian
solved:
func getFirstPageApplication(EMPTY:String,completionHandler: #escaping (_ response: AnyObject) -> ())
{
var strResponse = "null"
var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
request.httpMethod = "POST"
let postString = "EMAIL=\(EMPTY)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
DispatchQueue.main.async {
completionHandler({} as AnyObject)
}
} else {
if let usableData = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: usableData, options:
JSONSerialization.ReadingOptions.mutableContainers)
//print("worked")
//print(jsonResult) //this part works fine
DispatchQueue.main.async {
completionHandler(jsonResult as AnyObject)
}
} catch {
DispatchQueue.main.async {
completionHandler({} as AnyObject)
}
print("JSON Processing Failed")
}
}
}
}
task.resume()
}
Try using AnyObject instead of String in your completion handler and add JSONSerialization to serialize to json
func getFirstPageApplication(EMPTY:String,completionHandler: #escaping (_ response: AnyObject) -> ())
{
var strResponse = "null"
var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
request.httpMethod = "GET"
let postString = "EMAIL=\(EMPTY)"
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=\(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 = \(response)")
}
do {
let json:AnyObject? = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
print(parseJSON)
}
completionHandler(parseJSON)
}
}
task.resume()
}
Then you must be able to use this without problems
func initialFirstView()
{
RestApiManager.sharedInstance.getFirstPageApplication(EMPTY:"-"){
response in
print("res: \(response["sliders"])")
}
}
This code is not tested, so please let me know if works
Hope this helps

HTTP Send Request Parameter in Swift

i want to send request with username and password for getting authentication key from server, here is my code, i don't know how send to parameter with request, please help me for solve it.
let urlString = "http://services.84069.ir/Restful/PaymentService.svc/authenticate"
func recentProfileURL(parameter : [String:String]?) -> NSURL {
let component = NSURLComponents(string: urlString)!
var queryItem = [NSURLQueryItem]()
if let param = parameter {
for (key,value) in param {
let item = NSURLQueryItem(name: key, value: value)
queryItem.append(item)
}
}
component.queryItems = queryItem
return component.URL!
}
func fetchCode(completion completion: (ProfileResult) -> Void){
let request = NSURLRequest(URL: recentProfileURL(["UserName": self.userNameParam]))
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) in
let result = self.processUserProfileRequest(data: data, error: error)
completion(result)
})
task.resume()
}
I'm trying send username and password for getting authentication code from server how can send array of parameter instead of one parameter?
Try this I hope it would be helpful for you!!
let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/login.php")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
try this code
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
This should work for you:
var request = NSMutableURLRequest(URL: NSURL(string: ""http://services.84069.ir/Restful/PaymentService.svc/authenticate"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["UserName":"UserName you wish to send", "password":"Password you wish to send"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")`
}

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