Set timeout in Alamofire

后端 未结 14 1148
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 03:33

I am using Alamofire 4.0.1 and I want to set a timeout for my request. I tried the solutions gived in this question:

In the first case

相关标签:
14条回答
  • 2020-12-01 03:51

    As Matt said the problem is the following

    The difference here is that the initialized manager is not owned, and is deallocated shortly after it goes out of scope. As a result, any pending tasks are cancelled.

    The solution to this problem was written by rainypixels

    import Foundation import Alamofire

    class NetworkManager {
    
        var manager: Manager?
    
        init() {
            let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
            manager = Alamofire.Manager(configuration: configuration)
        }
    }
    

    And my own version

    class APIManager {
    
        private var sessionManager = Alamofire.SessionManager()
    
        func requestCards(_ days_range: Int, success: ((_ cards: [CardModel]) -> Void)?, fail: ((_ error: Error) -> Void)?) {
            DispatchQueue.global(qos: .background).async {
                let parameters = ["example" : 1]
    
                let headers = ["AUTH" : "Example"]
    
                let configuration = URLSessionConfiguration.default
                configuration.timeoutIntervalForRequest = 10
                self.sessionManager = Alamofire.SessionManager(configuration: configuration)
    
                self.sessionManager.request(URLs.cards.value, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
                    switch response.result {
                    case .success:
                        //do json stuff
                        guard let json = response.result.value as? [String : Any] else { return }
                        guard let result = json["result"] as? [[String : Any]] else { return }
                        let cards = Mapper<CardModel>().mapArray(JSONArray: result)
                        debugPrint("cards", cards.count)
                        success?(cards)
                    case .failure(let error):
                        if error._code == NSURLErrorTimedOut {
                            //timeout here
                            debugPrint("timeOut")
                        }
                        debugPrint("\n\ncard request failed with error:\n \(error)")
                        fail?(error)
                    }
                }
            }
        }
    }
    

    Can also make a manager for it

    import Alamofire
    
    struct AlamofireAppManager {
    
        static let shared: SessionManager = {
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 10
            let sessionManager = Alamofire.SessionManager(configuration: configuration)
            return sessionManager
        }()
    
    }
    
    0 讨论(0)
  • Please Try this:-

        let request = NSMutableURLRequest(url: URL(string: "")!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.timeoutInterval = 10 // 10 secs
        let values = ["key": "value"]
        request.httpBody = try! JSONSerialization.data(withJSONObject: values, options: [])
        Alamofire.request(request as! URLRequestConvertible).responseJSON {
            response in
            // do whatever you want here
        }
    
    0 讨论(0)
  • 2020-12-01 03:56

    If you don't want to build a UrlRequest yourself, you can still use Alamofire to build it.

        // set this flag to false so the request will not be sent until
        // resume() is called
        sessionManager.startRequestsImmediately = false
    
        var urlRequest = sessionManager.request(url,
                                                method: method,
                                                parameters: params,
                                                encoding: encoding,
                                                headers: allHeaders).request!
    
        urlRequest.timeoutInterval = 10
    
        let request = sessionManager.request(urlRequest).responseJSON { (result) in
            // use the result
        }
    
        // need to start the request
        request.resume()
    
    0 讨论(0)
  • 2020-12-01 03:57

    Try this:

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.timeoutIntervalForRequest = 4 // seconds
        configuration.timeoutIntervalForResource = 4
        self.alamoFireManager = Alamofire.Manager(configuration: configuration)
    

    Swift 3.0

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 4 // seconds
        configuration.timeoutIntervalForResource = 4
        self.alamoFireManager = Alamofire.SessionManager(configuration: configuration)
    
    0 讨论(0)
  • 2020-12-01 03:58

    I have same problem too, I think I found the solution. Try to declare SessionManager?or in your case alamofireManager in class, outside the function

    class ViewController: UIViewController {
       var alamoFireManager : SessionManager? // this line
    
       func alamofire(){
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 10
            configuration.timeoutIntervalForResource = 10
            alamoFireManager = Alamofire.SessionManager(configuration: configuration) // not in this line
    
            alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in
    
    
            switch (response.result) {
            case .success:
                     //Success....
                break
            case .failure(let error):
                   // failure...
                 break
           }
         }
       }
    
    }
    
    0 讨论(0)
  • 2020-12-01 03:59

    Alamofire 5.1 includes a new way to modify the request with a closure in the initializer:

    AF.request(url) { $0.timeoutInterval = 60 }
        .validate()
        .response { _ in // handle response here }
    
    0 讨论(0)
提交回复
热议问题