Alamofire doesn't make GET Request but call completion handler with Success - ios

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.

Related

WeatherKit with watchOS resulting with 401

My guess the issue is that the iOS app is com.example.MyApp and the bundle id for the watchOS app is com.example.MyApp.watchkitapp, so WeatherKit works perfectly on the iOS app after registering bundleID and request WeatherKit service.
But it does not work on watchOS, giving me 401 errors. I assume it is because of the bundleID, but maybe something else.
2022-06-25 08:58:58.999485-0500 JumpLog Watch App[72341:1201484] [WK_Geocode] failed to reverse geocode. location=CLLocationCoordinate2D(latitude: 37.62471885, longitude: -122.42857813), error=reverseGeocodeFailed(Error Domain=NMDeviceConnectionErrorDomain Code=2 "Timed out." UserInfo={NSDescription=Timed out.})
2022-06-25 08:58:59.019561-0500 JumpLog Watch App[72341:1201484] [Database] Attempting to invalidate an assertion that is no longer valid
2022-06-25 08:58:59.724802-0500 JumpLog Watch App[72341:1198856] [WeatherService] Encountered an error when fetching weather data subset; location=<+37.62471885,-122.42857813> +/- 5.00m (speed 34.21 mps / course 332.23) # 6/25/22, 8:56:58 AM Central Daylight Time, error=invalidJWTResponse(Optional(<NSHTTPURLResponse: 0x60000394bf20> { URL: https://weather-data.apple.com/v2/token } { Status Code: 401, Headers {
Connection = (
close
);
"Content-Length" = (
0
);
Date = (
"Sat, 25 Jun 2022 13:58:59 GMT"
);
Server = (
Apple
);
"Strict-Transport-Security" = (
"max-age=31536000; includeSubdomains"
);
"X-Apple-Origin" = (
"8961098f-b238-3714-ba44-5b569c861456"
);
"X-Cache" = (
"TCP_MISS from a23-33-47-144.deploy.akamaitechnologies.com (AkamaiGHost/10.8.2-41841244) (-)"
);
"X-Content-Type-Options" = (
nosniff
);
"X-Frame-Options" = (
SAMEORIGIN
);
"X-REQUEST-ID" = (
"2076edab-2346-4a50-83c1-e62f46aab9eb"
);
"X-XSS-Protection" = (
"1; mode=block"
);
} }))
And I have tried to register bundle id like com.example.MyApp.watchkitapp with my developer account, that results in error:
An attribute in the provided entity has invalid value
An App ID with Identifier 'com.example.MyApp.watchkitapp' is not available. Please enter a different string.
P.S. The real bundle ID is different, specific for my app.

How to fetch table data from azure SQL database using web app service in ios?

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.

Drawing directions from google map api

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.

Why the "Authorization" field in Http Headers in Alamofire set automatically?

I want to send my apiKey in headers in Alamofire to my web service.But no matter how many times I test it,I still cant to get the value of apiKey in my web service.
My web service always return this error,cause cant get the apiKey in the header.
{
"error": true,
"message": "Api key is missing"
}
This is how I make the request,I think I didnt do anything wrong,but the web service still cant get the value of apiKey.
let My_URL = "My_url"
let params : [String : Any]=["param1":value1,"param2":value2]
let headers : HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : apiKey //<--this is the value I need to
get in header of web service
]
Alamofire.request(MY_URL,method: .post ,parameters : params ,headers:headers).responseJSON {
response in
debugPrint(response)
}
My web service currently is serving for Android and Web version.Both running well,but I really no idea why the ApiKey in headers cant get it from webservice.
Totally no idea what is going wrong..Somebody please help!!!!
EDIT
I attach the result from debugPrint here,please take a look and let me know what is the problem,I suspect the problem is cause by the "Authorization" tag in the result below,the "Authorization" field is not the field I set,and the value as well,is not the value I want as well.
But why is this happen?? And how to solve this problem?
[Response]: <NSHTTPURLResponse: 0x60c00003d4c0> { URL: http://My_URL} { Status Code: 400, Headers {
"Access-Control-Allow-Headers" = (
Authorization
);
"Access-Control-Allow-Methods" = (
"GET, POST, PUT, DELETE, OPTIONS"
);
"Access-Control-Allow-Origin" = (
"*"
);
Authorization = ( // <--why this authorization appear
16ebe49c51039ddfbb09e5df8519e755 //this is not the value I set
);
Connection = (
close
);
"Content-Length" = (
45
);
"Content-Type" = (
"application/json"
);
Date = (
"Sun, 14 Dec 2017 14:20:59 GMT"
);
Server = (
"Apach(Ubuntu)"
);
"X-Powered-By" = (
"PHP/5.5.9-1"
);
} }
EDIT:
To solve the problem above,I read this following question
iOS Alamofire Incorrect Authorization Header
How to disable the URLCache completely with Alamofire
Therefore,I modify my request as below,but the problem still the same,the result of debugPrint is still same as above.
let configuration = URLSessionConfiguration.default
configuration.urlCache = nil
let sessionManager = Alamofire.SessionManager(configuration: configuration)
let params : [String : Any]=["param1":value1,"param2":value2]
let headers : HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : apiKey //<--this is the value I need to
get in header of web service
]
sessionManager.request(MY_URL,method: .post ,parameters : params ,headers:headers).responseJSON {
response in
debugPrint(response)
}.session.finishTasksAndInvalidate()
I know this question was asked long time ago, but to solving other persons issue I answer it.
Removing Authorization header value is not a bug make by alamofire lib. This key and some other keys are NSURLSession reserved key, so according to apple document value of these keys may change. To avoid this issue you must change the header name to something like Authorization-App or any other key confirmed by your API team.

Azure iOS Mobile Client: The server did not return the expected item

I'm updating the example Todo app from Microsoft Azure Mobile Services for iOS to use Table Storage instead of the default MSSQL backend. At the moment, when I try to insert a new item, I am getting the following error in the client:
2014-11-22 11:06:44.895 xxx[6942:869598] ERROR Error Domain=com.Microsoft.WindowsAzureMobileServices.ErrorDomain Code=-1201 "The server did not return the expected item." UserInfo=0x7a6b1040 {NSLocalizedDescription=The server did not return the expected item., com.Microsoft.WindowsAzureMobileServices.ErrorResponseKey=<NSHTTPURLResponse: 0x7a764cc0> { URL: https://xxx.azure-mobile.net/tables/TodoItem } { status code: 200, headers {
"Cache-Control" = "no-cache";
"Content-Encoding" = gzip;
"Content-Length" = 126;
"Content-Type" = "application/json";
Date = "Sat, 22 Nov 2014 19:06:44 GMT";
Server = "Microsoft-IIS/8.0";
Vary = "Accept-Encoding";
"X-Powered-By" = "ASP.NET";
"x-zumo-version" = "Zumo.master.0.1.6.4100.Runtime";
} }, com.Microsoft.WindowsAzureMobileServices.ErrorRequestKey=<NSMutableURLRequest: 0x7a7797a0> { URL: https://xxx.azure-mobile.net/tables/TodoItem }}
I have not changed the client code. The docs at https://github.com/Azure/azure-mobile-services/blob/master/sdk/iOS/src/MSJSONSerializer.m suggest that this error is an 'errorForExpectedItem' error, and it gets thrown in itemFromData:withOriginalItem:ensureDictionary:orError:.
This error started happening as I was trying to get the todoitem.read.js script to work; I am so far unable to get usable entities back from that script. Here's my todoitem.read.js as it now stands:
var azure = require('azure-storage');
var tableSvc = azure.createTableService();
function read(query, user, request) {
query = new azure.TableQuery()
.select()
.where('PartitionKey eq ?', 'learningazure');
console.log('query: ', query);
tableSvc.queryEntities('TodoItem',query, null, function(error, result, response) {
if(!error) {
// query was successful
// add the count to the response dictionary
response.count = response.body.value.length;
response.results = result.entries;
request.respond(200, response);
} else {
console.log('Error calling read()');
console.log(error);
}
});
}
Any suggestions?
Derp. My error: in todoitem.insert.js, in the insert() function, I was never calling request.respond().
Now the node.js code is returning data, but it's still not showing up in the iOS client. More reading required.

Resources