Reputation: 1023
I am using google distance matrix API and i am using following code
let headers: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]
let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=\(start)&destinations=\(end)&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg"
let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]
Alamofire.request( url, method: .get, encoding: JSONEncoding.default, headers : header) .responseString { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result)
}
as per this Unable to fetch Response For Google Distance matrix in Swift i am passing header but still i am getting following error.
Here is my URL with start and end "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=Nanpura, Surat, Gujarat 395008, India&destinations=Adajan, Surat, Gujarat, India&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg "
Upvotes: 1
Views: 1617
Reputation: 5754
I checked the request and it is working fine. I guess you are missing privacy setting in info.plist
Upvotes: 2
Reputation: 6555
You should encode url, try with this
let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=Nanpura, Surat, Gujarat 395008, India&destinations=Adajan, Surat, Gujarat, India&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg"
let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]
Alamofire.request(encodedUrl! , method: .get,encoding: JSONEncoding.default, headers: header)
.responseJSON { (data) in
print(data)
}
this will also work,
Alamofire.request(encodedUrl!, method: .get,encoding: JSONEncoding.default, headers: header)
.responseString {response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result)
}
Response will be like this,
SUCCESS: {
"destination_addresses" = (
"Adajan, Surat, Gujarat, India"
);
"origin_addresses" = (
"Nanpura, Surat, Gujarat 395008, India"
);
rows = (
{
elements = (
{
distance = {
text = "2.4 km";
value = 2433;
};
duration = {
text = "6 mins";
value = 373;
};
status = OK;
}
);
}
);
status = OK;
}
Upvotes: 3