当前位置:  开发笔记 > 前端 > 正文

在Alamofire设置超时

如何解决《在Alamofire设置超时》经验,为你挑选了6个好方法。

我正在使用Alamofire 4.0.1,我想为我的请求设置超时.我试过这个问题给出的解决方案:

在第一种情况下,它会抛出NSURLErrorDomain(正确设置超时):

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10

    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
            .responseJSON {
                response in
                switch (response.result) {
                case .success:
                    //do json stuff
                    break
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        //timeout here
                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
                }
            }

在第二种情况下,超时不会被替换,仍然设置为60秒.

let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 10

manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])

我在ios 10.1中运行

我的代码:(它不起作用)

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10 // seconds
    configuration.timeoutIntervalForResource = 10
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)

    alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in


        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
            // failure...
            break
        }
    }

解决了Alamofire github线程: Alamofire 4.3.0设置超时抛出NSURLErrorDomain错误#1931



1> Kamal Thakur..:

请试试这个: -

    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
    }


嗯,我似乎得到这个错误:无法将'NSMutableURLRequest'类型的值转换为'Alamofire.URLRequestConvertible'.
尝试使用“ var request = URLRequest(url:url)”,而不是“ let request = NSMutableURLRequest(url:url)”

2> Aldo Lazuard..:

我也有同样的问题,我想我找到了解决方案.尝试在课堂上声明SessionManager?或在你的情况下alamofireManager,在函数之外

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
       }
     }
   }

}



3> Jason Bourne..:

试试这个:

    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)



4> Alexander Kh..:

正如马特所说,问题如下

这里的区别在于初始化的管理器不是拥有的,并且在它超出范围后不久就会被释放.因此,任何待处理的任务都将被取消.

这个问题的解决方案是由rainypixels编写的

import Foundation导入Alamofire

class NetworkManager {

    var manager: Manager?

    init() {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        manager = Alamofire.Manager(configuration: configuration)
    }
}

而我自己的版本

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().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)
                }
            }
        }
    }
}

也可以为它做一个经理

import Alamofire

struct AlamofireAppManager {

    static let shared: SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        let sessionManager = Alamofire.SessionManager(configuration: configuration)
        return sessionManager
    }()

}



5> ƒernando Val..:

基于@ kamal-thakur的回复.

斯威夫特3:

var request = URLRequest(url: NSURL.init(string: "YOUR_URL") as! URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10 // 10 secs
let postString = "param1=\(var1)¶m2=\(var2)"
request.httpBody = postString.data(using: .utf8)
Alamofire.request(request).responseJSON {
    response in
    // do whatever you want here
}



6> 小智..:

如果您使用的是Alamofire的一个实例,则可以像下面这样创建一个惰性变量:

   private lazy var alamoFireManager: SessionManager? = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)
    return alamoFireManager

}()

适用于Swift 4.2

推荐阅读
落单鸟人
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有