Alamofire timeout url - swift

I am using the Alamofire Swift library
Alamofire.request
(RestApiManager.sharedInstance.baseURL+"login?language="+lang,
method: .post,
parameters: requestDictionary,
encoding: URLEncoding.httpBody,
headers: headers
).responseObject(keyPath: "") { (response: DataResponse<User>) in
let user = response.result.value
print(user?.status)
print(user?.message)
}
So simply, I want to put a timeout of 60 seconds on every call I make.And i like to give a message connection timeout after 60 seconds. I also want to know, if there exists an internet connection or not. If it doesnt exist, I like to avoid calling alamofire.

Here's the Swift 3.0 / Alamofire 4.0 code to get an alamofireManager that has a 60 second timeout.
You need create a global variable for the request manager:
var alamoFireManager = Alamofire.Manager.sharedInstance
And after configure the custom parameters:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 60 // seconds
configuration.timeoutIntervalForResource = 60
self.alamoFireManager = Alamofire.Manager(configuration: configuration)

Related

Alamofire session configurations are not reflected in the request

Alamofire Version: 5.1
We are modifying our alamofire session configuration as following:
let apiManager: Session = {
let configuration = URLSessionConfiguration.af.default
configuration.timeoutIntervalForRequest = 20
configuration.requestCachePolicy = .reloadIgnoringCacheData
configuration.urlCache = nil
let manager = Alamofire.Session(
configuration: configuration,
cachedResponseHandler: ResponseCacher(behavior: .doNotCache)
)
return manager
}()
And we are making the request as following
apiManager.request(
url,
method: .post,
parameters: requestBodyParameters,
encoding: JSONEncoding.default,
headers: generateHeaders(enableAuth: authorisation) // to generate headers
)
.validate(statusCode: 200..<300)
.responseJSON { response in
print(response)
}
}
}
But the request configurations is not updated, they remain at default values
[Timeout]
60
[Cache policy]
UseProtocolCachePolicy
You're looking at the URLRequest generated by Alamofire which doesn't include the URLSession-level configuration, and which will never reflect the cache customization. If you want to see the actual URLRequest being performed after it passes through both Alamofire and URLSession, you can access the latest URLSessionTask that the Alamofire Request (in this case a DataRequest) performed by using request.task. However, like I said, this will never reflect the other behaviors you've attached, like a ResponseCacher, since those exist outside of the request pipeline.

Alamofire - Add a timeout if there is no response

I have a JSON call using Alamofire, it works well except if the query on the server is not responding. If the endpoint times out then Alamofire does give a timeout error but recently the endpoint was working but MSSQL on the server was not responding. In that case, the SVProgress would just spin and wait for the server to return the response and would not timeout.
How can I add a timeout to the below code so that if the server is not responding after x seconds I get an error?
I'm using Swift 5.
SVProgressHUD.show()
let apiEndpoint: String = "https://intelipos.dynalias.net/iocserver/MobileApp.aspx?action=MobileApp"
let headers = HTTPHeaders(["Content-Type" : "application/json","WebSiteAppID":self.webSiteAppID])
var param = [String: Any?]()
param["Command"] = "GetSales"
let keychain = KeychainSwift()
let sessionID = keychain.get("adminSessionID")!.base64Decoded()!
let strParam = jsonToString(json: ["SessionID":sessionID])
param["Data"] = strParam?.base64Encoded()
param["Signature"] = strParam?.base64Encoded()?.sha256Signature()
let request = AF.request(URL(string: apiEndpoint)!, method: .post, parameters: param as Parameters, encoding: JSONEncoding.default, headers: headers)
You just need to set the timeout interval of your url request to your desired value.
request.timeoutInterval = 30

Can async image download have timeout or do I need NSURLSession?

Can this image download technique use timeouts: Why doesn't image load on main thread??
Or must I use NSURLSession instead if I want to use timeouts?
You are looking for the timeoutintervalForResource property. If you use URLSession.shared, the default timeout is 7 days. If you want to use a different timeout, you need to create your own session:
let config = URLSessionConfiguration.default
config.timeoutIntervalForResource = 60 // timeout, in seconds
// A 20 MB image from NASA
let url = URL(string: "https://www.nasa.gov/sites/default/files/thumbnails/image/hs-2015-02-a-hires_jpg.jpg")!
let session = URLSession(configuration: config)
session.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
}
// do something
}.resume()
Lower the timeout enough and you will see a timeout error. Note that URLSessionConfiguration has 2 timeouts: timeoutIntervalForResource and timeoutIntervalForRequest:
...Resource is the time to wait for whole network operation to finish (default is 7 days)
...Request is the time to wait for next chunk of data to arrive (default is 60 seconds)
If your goal is to download something in x minutes, using ...Resource. If your goal is "network must response within x seconds or it's down", use ...Request.
No, you don't have to use NSURLSession. The timeout properties are in URLSesssionConfiguration and you just need to create an instance of URLSession using your desired configuration.
So, rather than using URLSession.shared directly you would need to make your own instance of URLSession and start the dataTask from that instance.
You are probably interested in timeoutIntervalForResource, which I think defaults to 7 days.
Here is a relevant Swift fragment from the answer to this question:
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
let session = URLSession(configuration: sessionConfig)

How to upload zip data with alamofire?

I try to upload data using Alamofire
Issue is: if I try to upload image from project it works ok, but if I try to upload zip dir I got error and timeout exception
There is my code which produces timeout exception
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10 // seconds
configuration.timeoutIntervalForResource = 10
alamoFireManager = Alamofire.SessionManager(configuration: configuration)
let fileData = FileManager.default.contents(atPath: filePath)
alamoFireManager.upload(fileData,
to: url,
method: .post,
headers: headers)
.validate()
.responseJSON {}
And here is code which works fine
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10 // seconds
configuration.timeoutIntervalForResource = 10
alamoFireManager = Alamofire.SessionManager(configuration: configuration)
let fileURL = Bundle.main.url(forResource: "MyImage", withExtension: "jpg")
alamoFireManager.upload(fileURL,
to: url,
method: .post,
headers: headers)
.validate()
.responseJSON {}
I tried to pass Data() to upload request also I tried pass reference to zip dit URL to upload request, also I tried InputStream(url: fileURL!)! but without success...
What am I doing wrong? how to send zip data to the server?
if there is some question feel free to ask!
Eventually, I found the issue, server side does not accept my request. Also, there is some confusion, because if I try to download an image file from my project it works, but if the file is selected from the document directory then there is an issue.
Anyway if someone has a similar issue try to check your server side.
Try to check if your request came to server and with content inside.

Setting client-side timeout per request with Alamofire [swift]?

I'm trying to set a client-side timeout per request for Alamofire for Swift. The lead architect told me to set this on NSURLRequest, but I'm completely confused on how to actually do that in practice.
Can someone who has done this give an example? Thanks!
I think this code may works.
var alamofireManager : Alamofire.Manager?
func some(){
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForResource = 2 // seconds
self.alamofireManager = Alamofire.Manager(configuration: configuration)
self.alamofireManager!.request(.GET, "http://example.com/")
.response { (request, response, data, error) in
}
}
This is how you can use a per-request timeout using URLRequest:
Alamofire.request(URLRequest(url: ..., cachePolicy: ..., timeoutInterval: 10))
.response(...)