Alamofire timeout not working in Swift 3

2019-09-17 05:16发布

I am using Alamofire for network request and want to add timeout. But Alamofire's function is not working. Nothing happens when I write the following code

let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 1 // not working, 20 secs normally (1 just for try)

    manager.request(url, method: method, parameters: params)
        .responseJSON { response in
            print(response)
            ...

When I try without Alamofire for network request, timeout working successfully. But there are other mistakes.

var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 1 // 20 secs normally (1 just for try)
request.httpBody = try! JSONSerialization.data(withJSONObject: params!)
...    

So, how can i add timeout for Alamofire in Swift 3?

2条回答
可以哭但决不认输i
2楼-- · 2019-09-17 06:05

You can't modify the values of a URLSessionConfiguration after it has be added to a URLSession, so attempting to manipulate Alamofire.SesssionManager.default.session.configuration will always fail. To properly change the configuration values, follow the Alamofire documentation for instantiating your own SessionManager. For example:

var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"

let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = defaultHeaders

let sessionManager = Alamofire.SessionManager(configuration: configuration)
查看更多
男人必须洒脱
3楼-- · 2019-09-17 06:09

Finally I found a solution to this answer: https://stackoverflow.com/a/44948686/7825024

This configuration code does not work when I add my function, but it works when I add it to AppDelegate!

AppDelegate.swift

import UIKit

var AFManager = SessionManager()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 5 // seconds
        configuration.timeoutIntervalForResource = 5 //seconds
        AFManager = Alamofire.SessionManager(configuration: configuration)

        return true
    }
    ...
}

Example:

AFManager.request("yourURL", method: .post, parameters: parameters).responseJSON { response in
    ...
}
查看更多
登录 后发表回答