I am trying to draw a direction line from marker to another. I already turned on directions in google map api. I got this function in here (SO). I understand what its doing but I can not get it to work. The routes array returns empty. I have tried multiple points for tests. Here is the functions:
func drawPath2(origin: CLLocationCoordinate2D, destination: CLLocationCoordinate2D)
{
let origin = "\(origin.latitude),\(origin.longitude)"
let destination = "\(destination.latitude),\(destination.longitude)"
let apiKey = "Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
guard let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ") else {return}
Alamofire.request(url).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
let json = try! JSON(data: response.data!)
let routes = json["routes"].arrayValue
//remove this after test
print(routes.count)
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSMutablePath.init(fromEncodedPath: points!)
let polyline = GMSPolyline.init(path: path)
polyline.map = self.mapView
}
}
}
Here is the print() results:
Optional(https://maps.googleapis.com/maps/api/directions/json?origin=49.18705,-123.107261&destination=49.1844,-123.1052&mode=driving&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ)
Optional(<NSHTTPURLResponse: 0x6000024c5ba0> { URL: https://maps.googleapis.com/maps/api/directions/json?origin=49.18705,-123.107261&destination=49.1844,-123.1052&mode=driving&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ } { Status Code: 200, Headers {
"Cache-Control" = (
"no-cache, must-revalidate"
);
"Content-Encoding" = (
gzip
);
"Content-Length" = (
130
);
"Content-Type" = (
"application/json; charset=UTF-8"
);
Date = (
"Mon, 10 Dec 2018 22:28:52 GMT"
);
Expires = (
"Fri, 01 Jan 1990 00:00:00 GMT"
);
Pragma = (
"no-cache"
);
Server = (
mafe
);
Vary = (
"Accept-Language"
);
"alt-svc" = (
"quic=\":443\"; ma=2592000; v=\"44,43,39,35\""
);
"x-frame-options" = (
SAMEORIGIN
);
"x-xss-protection" = (
"1; mode=block"
);
} })
Optional(129 bytes)
SUCCESS
0
I do not see data in there at all. I think something is wrong with URL or request. Please help me sirs and madams.
I suspect, your api key is not authorized to use this service. You can verify by printing json
print(json)
You should see this in response where the routes array is empty,
{
"error_message" = "This API project is not authorized to use this API.";
routes = (
);
status = "REQUEST_DENIED";
}
Go to Google cloud console and create a new project and enable Direction API. API Libary
And Place your API Key in your url
See this Link It helps you for sample API and Response for Google Direction API.
Related
I try to get some data from a grqphql endpoint with F#.
I use Fsharp.Data
let apiQuery = """query findData {
apiData(Model:{
PageNumber: 1,
PageSize: 100
})
{
ErrorMessage Success ValidationResult TotalCount
Data{
ItemId
}
}
}"""
let queryGraphQl () =
Http.RequestString
( apiUrl,
headers = [ ContentType HttpContentTypes.Json;
Authorization ("bearer " + token)
],
body =
TextRequest apiQuery
)
But I get (500) Internal Server Error
The same in Python works fine:
query_headers = {
"Authorization": 'bearer %s' % token,
'Content-Type': 'application/json'
}
response = requests.post(url, json={'query': apiQuery}, headers=query_headers)
Any suggestions what I am missing?
In Postman I have to add
Content-Length and Host like to be calculated when request is sent.
It appears that the F# and Python code is not equivalent. The Python code contains additional query keyword in the payload.
I don't know the specifics of your particular endpoint, but I wrote similar code using one of the public interfaces.
open System.Net
open FSharp.Data
open FSharp.Data.HttpRequestHeaders
let key = "********-****-****-****-*************"
let uri k = $"https://api.everbase.co/graphql?apikey={k}"
let gurl = uri key
let apiQuery = """{ "query" :
"{ client { ipAddress { country { name } city { name } } } }"
}"""
let connectToGraph apiUrl apiQuery =
try
let res = Http.RequestString( url = apiUrl, httpMethod="POST", body = TextRequest apiQuery, headers = [ ContentType HttpContentTypes.Json; UserAgent "mozilla" ])
res
with
| _ as ex -> ex.Message
[<EntryPoint>]
let main argv =
let res = connectToGraph gurl apiQuery
printf "Response: %A" res
0
I suppose you should separate the query in your F# code from the rest of the definition with a ':'. Also the actual payload should be wrapped in quotes/double quotes to form a valid Json value.
I followed this document to connect iOS (Swift) app to Azure, this is my code to connect database to my app:
let client = MSClient(applicationURLString: "https://<webappname>.azurewebsites.net")
let table = client.table(withName: "User")
table.read(completion: { (items, error) in
print(String(describing: error))
})
and when I run the app, azure gives below response:
UserInfo={com.Microsoft.MicrosoftAzureMobile.ErrorResponseKey= { URL:
https://.webappname.azurewebsites.net/tables/User } { Status Code: 404, Headers {
"Content-Length" = ( 0 ); Date = ( "Mon, 16 Sep 2019 06:01:42 GMT" );
Server = ( Kestrel ); "Set-Cookie" = (
"ARRAffinity=9d50440330c6da9f063baa60c470baaccbb1dd7c2e349666c42c6bd54274ea59;Path=/;HttpOnly;Domain=.azurewebsites.net"
); "X-Powered-By" = ( "ASP.NET" ); } }, NSLocalizedDescription=,
com.Microsoft.MicrosoftAzureMobile.ErrorRequestKey= { URL:
https://.webappname.azurewebsites.net/tables/User }})
Any help will be appreciated.
As an object, I have a problem with Alamofire (the same happens with AFNetworking) with an App Distributed internally which I can't debug the real Device; in particular with the iPhone X iOS 12.1.3 and only one device have this problem.
The requests work fine for all Testers, but in one iPhone X, without apparent reason, the Alamofire/AFNetwork, GET/POST, requests stop to come to the Web Service (I have access to real time log of WS and there are no request), but it seems that completion block with Success was called and the App follow the correct flow.
I can't debug this device and I don't know what happens; The Tester does not do any particular action to get this error.
This is one request of the many that do not work; I repeat, all work fine for an hour, after I don't know what happens, kill and reopen the App doesn't work.
Alamofire.request(completePath, method: .get, parameters: nil, encoding: URLEncoding.default, headers: ServiceSupport.sharedInstance.headerAlamofire()).responseJSON { (responseObject) in
if let json = responseObject.result.value {
if(ServiceSupport().headerIsOk(dictResponse: json as! NSDictionary)) {
completion(SUCCESS, "")
} else {
completion(FAIL, "ERROR")
}
} else {
completion(FAIL, "ERROR")
}
}
}
Someone can help me? Has anyone happened?
Thanks to all.
Edit:
The server should return different data when the request stop coming to WebService; Moreover I have the same problem, with the same Device, with AFNetworking.
Edit 2:
Response Header
[Response]: { URL: http://******/configuration } { Status Code: 200, Headers {
Connection = (
"Keep-Alive"
);
"Content-Length" = (
1060
);
"Content-Type" = (
"application/json;charset=UTF-8"
);
Date = (
"Thu, 31 Jan 2019 13:03:23 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Server = (
Apache
);
"Set-Cookie" = (
"JSESSIONID=96A0D1E4419A353E6115E34451793951; Path=/; HttpOnly"
);
"X-Frame-Options" = (
SAMEORIGIN
);
"X-XSS-Protection" = (
"1; mode=block"
);
} }
Thanks to all, the problem was the Cache!
URLCache.shared.removeAllCachedResponses()
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
This work for me.
First of all, we are using below code so as the api's works only on mobile devices and not on browsers per say.
"
$iPod = stripos($_SERVER['HTTP_USER_AGENT'], "iPod");
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'], "iPhone");
$iPad = stripos($_SERVER['HTTP_USER_AGENT'], "iPad");
$Android = stripos($_SERVER['HTTP_USER_AGENT'], "Android");
$json_data = json_decode(file_get_contents('php://input'));
if ($json_data) {
$username_1 = $json_data->username;
if ($Android || $iPad || $iPhone || $iPod) {}
Secondly, the api's are working on android(using volley) and in ios objective-c using AFNetworking. But, now i am porting the project to swift3 and i am using "Alamofire" for network calls.
Method:: (This is how i make POST request):
let headers : HTTPHeaders = [
"Accept" : "application/json"
]
Alamofire.request("API URL", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON{
response in
if let json = response.result.value{
}
But, i am getting error 404, which we usually get when we hit api in browser.
After that i removed that backend check and the request worked fine and got the proper response. But, we can't remove that check. So help me, if i am making any mistakes with headers of something else.
This is what i am getting in debugPrint(response)::
{ status code: 200, headers {
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 84;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 14 Sep 2017 17:03:17 GMT";
Expires = "Thu, 19 Nov 1981 08:52:00 GMT";
"Keep-Alive" = "timeout=5";
Pragma = "no-cache";
Server = "Apache/2.4.25";
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.6.31";
} }
[Data]: 80 bytes
[Result]: SUCCESS: {
"is_valid" = 0;
status = 404;
"status_message" = "access denied";
success = 0;
}
Alomafire sends a default header parameter User-Agent alright but its value is something like this iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0.
This is from their readme:
You can obviously provide your own custom headers:
let headers: HTTPHeaders = [
"User-Agent": "iPhone",
"Accept": "application/json"
]
Alamofire.request("<Ypur URL>", headers: headers)
.responseJSON { response in
debugPrint(response)
}
Or if you want to keep other default header parameters
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["User-Agent"] = "iPhone"
I have the following code to send POST data to my server:
var headers:Array = [
new URLRequestHeader("api_access_token", ACCESS_TOKEN),
new URLRequestHeader("api_secret", SECRET),
new URLRequestHeader("Content-type", "application/json")
];
var base_url = "http://example.com/";
var complete_func:Function;
function postRequest(url:String, params:Object, response_func:Function){
complete_func = response_func;
var request = new URLRequest(base_url+url);
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.data = JSON.stringify(params);
// Handlers
var postLoader = new URLLoader();
postLoader.addEventListener(Event.COMPLETE, parseResponse);
postLoader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent){ trace(e); });
postLoader.load(request);
}
function parseResponse(e:Event){
var data = e.target.data;
trace(data);
var json_data = JSON.parse(data);
complete_func(json_data);
}
Problem is, on my server, when I use var_dump($_POST) nothing but an empty array is returned. I don't know why this is the case. I have done traces on params and url parameters which contain relavent data.
The params I am sending are:
var customerDetails:Object = new Object();
customerDetails.first_name = firstNameField.text;
customerDetails.last_name = lastNameField.text;
customerDetails.dob = dobField.text;
customerDetails.email = emailField.text;
The headers retrieved by PHP's list_headers() returns:
array(6) { [0]=> string(24) "X-Powered-By: PHP/5.4.30" [1]=> string(38) "Expires: Thu, 19 Nov 1981 08:52:00 GMT" [2]=> string(77) "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" [3]=> string(16) "Pragma: no-cache" [4]=> string(44) "api_secret: example_secret" [5]=> string(50) "api_access_token: example_access" }
I am using Air 16.0 for iOS with ActionScript 3
Any help would be great. I don't know if this is a cross-domain policy issue.
P.S. Works fine with a GET request.
Use the right dataFormat:
loader.dataFormat = URLLoaderDataFormat.VARIABLES
As3 code is valid. You need improve from server side php code.. Please try this ..
<?php
$body = #file_get_contents('php://input');
$jsn = json_decode($body);
echo $jsn->first_name;
echo $jsn->last_name;
echo $jsn->dob;
echo $jsn->email;
?>