Unable to get response from Google distance matrix api - ios

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 "

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

I checked the request and it is working fine. I guess you are missing privacy setting in info.plist

Related

Vize.ai Image Recognition in iOS app

I am trying to implement the Vize.ai image recognition in an iOS app using Swift 4.
In their documentation this is the code example they give for Objective C:
NSDictionary *headers = #{#"Authorization": #"JWT {your JWT token}", #"Content-Type": #"application/x-www-form-urlencoded", #"Accept": #"text/plain"};
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
[request setUrl:#"http://cl-api.vize.ai/{your task ID}?image={path/myimage.png}"];
[request setHeaders:headers];
}] asundefinedAsync:^(UNIHTTPundefinedResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
}];
As you can see I have to pass an image path to the request. In my app the user can either chose to analyse a default picture that is added to the project's assets folder or add from library/take a photo.
What is that image Path supposed to be in this example?
Here is how I am making the request with Swift 4, any image path I am adding to it it gives me an "missing image or url" response error back:
let headers: HTTPHeaders = [
"Authorization": "JWT \(jwtToken)",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
]
let url = "https://cl-api.vize.ai/\(taskID)?image=\(imagePath)"
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
}
Any help is greatly appreciated. Thanks!
So I managed to find a solution for this using multipart form data. Here is the complete code for it.
func getVizeImageAnalysis(image: UIImage) {
let headers: HTTPHeaders = [
"Authorization": "JWT \(jwtToken)",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
]
let url = "https://cl-api.vize.ai/\(taskID)"
manager.upload(multipartFormData: { multiPartData in
// Add image
if let imageData = UIImageJPEGRepresentation(image, 0.8) {
multiPartData.append(imageData, withName: "image", fileName: "pickedImage", mimeType: "image/jpeg")
}
}, to: url, method: .post, headers: headers, encodingCompletion: {
encodingResult in
switch encodingResult {
case .success(let request, _, _):
request.responseJSON{ response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
})
}

{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; } In swift

I am trying with this but every time I will get
{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; }
Request String:
let headers = [ "Content-Type" : "application/x-www-form-urlencoded"]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["grant_type":"authorization_code","code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"387376833747-12pbtud9tepr4di0insdhc0d4qpf5e9m.apps.googleusercontent.com","client_secret":"xOacVhLavM9fH8SpOK4I2dRJ","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Also try with passing request parameter like this but still doesn't work for me.
You can't send appended parameter with url while post request.
Pass parameter as below this
let headers = [ "Content-Type" : "application/x-www-form-urlencoded","grant_type" : "authorization_code"" ]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"apps.googleusercontent.com","client_secret":"","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
These error invalid_request occurs only below cases so please check with your server side what is missing or invalid.
The request is missing a required parameter, includes an unsupported
or invalid parameter value, repeats a parameter,includes multiple
credentials, utilizes more than one mechanism for authenticating the
client, or is otherwise malformed.

Alamofire 4.3 can't send JSON request

Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :
{"ClientID":"55050","AdminId":"myemail","Password":"123"}
content-type → application/json; charset=utf-8
and here's my code :
import Alamofire
func doLogin(username:String ,password:String) {
let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]
Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
response in
print(response)
})
and here's the response which i am getting
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
By reading the documentation i just need to put header to set the request as application/json
so i added extra parameter header :
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
}
and now it's working perfectly thanks everyone for trying to help :)
It seems you must have missed header in your request. So, there has been no response.
Your header must be a dictionary [String: String].
let header = ["Content-Type" : "application/json"]
And your sample request should be:
Alamofire.request(getCategoryPath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
}
print(response.result.value)
}

Twitter API in SWIFT via Alamofire

I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply cant get it working
My Code looks like:
func TWITTER_getPosts(username:String){
let headers = [
"screen_name": "username",
"authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
"include_rts": "false"
]
Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I Always end in a
errors = (
{
code = 215;
message = "Bad Authentication data.";
One of the parameters for the request method is incorrect.
If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
headers: headers should be the way to go.

Alamofire HTTP requests fails

I made some HTTP requests using Alamofire. Some request has been succeeded and some are failed.
error is Invalid value around character 0.
Failed request gave me above error.
bellow i have mentioned a sample code which failed.
let parameters = ["amount": ["10"], "payment_method": ["paypal"], "date": ["2015-11-25"], "details": ["Payment description"]]
let headers = [
"Accept": "*/*",
"Content-Type": "application/json"
]
let url = "https://livetest.somedomain.com/api/invs/LAT1j5da99PdPg/payments?auth_token=pbtTEPNki3hUhGBuPX3d"
Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON, headers: headers)
.responseJSON { response in
let results = response.result
print(results)
print(response.debugDescription)
}
Please help me to find the issue
This issue was happened because of wrong format of JSON passing. Then i changed the parameter as follows
let parameters = ["payment":["amount": "100" , "payment_method": "check", "date": "2015-11-25", "details": "Payment description dimuth Lasantha"]]
Now it passes the correct format which is
{
payment: {
"amount" : "100",
"payment_method" : "check",
.....
}
}

Resources