I'm using alamorefire to make calls to an API, but I figured that if I put the app in the background, the call will pause and I don't want that. I want it to load and then, when I bring the app to the foreground, I can use the requested data on the UI. How can this be done? At the moment I just do plain requests like this:
Alamofire.request(url, method: .get, parameters: params, headers: header())
.responseJSON{response in switch response.result {
I've tried using the following alamofire configuration:
let configuration = URLSessionConfiguration.background(withIdentifier: "com.cmpny.myapp.background")
let manager = Alamofire.SessionManager(configuration: configuration)
manager.request(url, method: .get, parameters: params, headers: headers())
This gives me the following error:
Request failed with error: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=http://url, NSLocalizedDescription=cancelled, NSErrorFailingURLKey=http://url}
You should use UIBackgroundTaskIdentifier for this purpose.
Apple doc:
https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiratio
Similar question:
https://stackoverflow.com/a/31751337/1689376
Hope this helps ;)
Related
I'm using background fetch in an iOS app to schedule some notifications and I need to fetch some data from server But when i create an Alamofire request the surver returns the data but alamofire does not calles my compilation handler (responseString)
the exact same code works perfectly while my app is on forground.
Alamofire.request(url, method: method ?? HTTPMethod.get, parameters: parameters,
encoding: encoding ?? URLEncoding.default, headers: headers)
.responseString{
(afResponse : DataResponse<String>) -> Void in
....
}
I used AlamofireNetworkActivityLogger to check weather the response is created and fetched and the result was true. but my compilation handler not getting called!
any thing else should I consider while using Alamofire in background?
Have you tested if it is working as suggested in Alamofire network calls not being run in background thread
We may have to start the call from background thread instead of the main thread (as it is the default behaviour).
I am facing to
Error - The network connection was lost.
I am using RealmSwift and Alamofire in my project.
This is a real estate app and when ever I am searching properties suddenly I am facing to this error without any exception or error and if I searching again than it works properly.
I don't understand why I am facing this issue.
I am using following code for JSON encoding:
Alamofire
.request(url, method: method, parameters: parameters, encoding: encoding, headers: header)
.responseJSON(completionHandler: { (response) in
Please help.
Are you encoding the parameters as JSON in the request body? If so, encode them as URL:
Alamofire.request(.GET, myURLString, parameters: parameters, encoding: .URL, headers: myHeaders)
I am a newbie to iOS and using Alamofire in my app. Everything is working fine. Now I want to implement network errors. I have searched about it and here are my findings:
We can implment request timed out in the following way:
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 10
let urlVerifyEmail = ####
manager.request(urlVerifyEmail, method: .post, parameters: ["user_email" : email], encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: { response in
switch response.result {
case .success:
print (“success”)
case .failure(let serverError):
if (serverError._code == NSURLErrorTimedOut)
{
print(”Request timed out”)
}
else
{
print(”Error sending request to server”)
}
}
}
)
I have read there official docs too. However I am not having much clarity.
What does request timed out actually mean? Does it mean that the app is taking too long to send the request? or server is taking too long to send the response back?
What are other types or network errors in Alamofire? What if the connection wasn't successfully made? What if it broke while the request was getting sent? What if it broke while the response was coming back?
If error code for request timed out is -1001 then what are the codes for other network errors? In order to provide the users with the best experience, which is the best approach to cover all of network errors?
I am trying to make a Alamofire POST request. This is how I am making the request..
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers : headers)
.responseString { response in
print(response.result)
}
Though I am getting the result as 'SUCCESS', the status code is always shown as 405 while it should have been 200. In the 'encoding' part of the request, I have tried everything like JSONEncoding.default,JSONEncoding.prettyPrinted, URLEncoding.httpbody...but always the status code is still 405. Can anyone please help? Thanks in advance...
This is the solution for this issue...A couple of changes had to be made..
The header which was given was this: let headers = [ "Content-Type" : "application/json"]. But it had to be let headers = [ "Content-Type":"application/x-www-form-urlencoded"].
Also the encoding should be given as URLEncoding.httpBody.
Making these changes made it work fine...
I think problem is with your server because this status code only comes when server disable the api
The HTTP 405 Method Not Allowed response status code indicates that
the request method is known by the server but has been disabled and
cannot be used. The two mandatory methods, GET and HEAD, must never be
disabled and should not return this error code.
So Contact your server(backend developer), make sure your url is correct
I have faced same problem. The API endpoint worked fine with Android Retrofit, also tested with PostMan. Also the header's Content-Type was application/json.
It was really strange bug. I've used Fiddler to check the response.
The error message was
The requested resource does not support http method 'T'/'ST'.
I used GET/POST method, but it said I was using the T/ST, instead of GET/POST
I found answer from the Alamofire's issues.
When I called the API endpoint without parameters, I used the blank dictionary as parameter.
Alamofire.request("URL",
method: .get,
parameters: [:],
encoding: JSONEncoding.default).responseString(completionHandler: completionHandler)
I changed it to nil
Alamofire.request("URL",
method: .get,
parameters: nil,
encoding: JSONEncoding.default).responseString(completionHandler: completionHandler)
After that, it worked fine.
Hope it will help you. Cheers!
Try to replace:
responseString with responseJSON
AND URLEncoding(destination: .queryString) with URLEncoding.default
LIKE:
Alamofire.request(strURL, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
//Do something
}
I am trying to make a POST request using latest Alamofire 4.0.0 / Swift 3 passing JSON in the request.
The request calls a wildfly server and takes up to a minute to return with data.
However, I constantly get a server error java.io.IOException: UT010029: Stream is closed.
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"Accept": "application/json",
"Connection": "Keep-Alive"
]
Alamofire.request("myUrl", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.validate().responseJSON { response in
print("Response")
print(response)
}
}
Alamofire doesn't complain at all and doesn't log anything.
I have tried other requests to the same server/service that return instantly and I get into the completion handler.
Is this just a timeout issue? If so how can I adjust it?
I was getting a very similar problem with GET requests. Turns out I was passing an empty dictionary [:] as parameters to the request method. Omitting the parameters: completely in the call solved the issue.