我使用的是Alamofire 4.0.1和I want to set a timeout for my request.我try 了这question条中给出的解决方案:

In the first case,则抛出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
                }
            }

In the second case时,超时未被替换,仍然设置为60秒.

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

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

I am running in ios 10.1

My code:(不起作用)

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

Solved Alamofire github thread: Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error #1931

推荐答案

根据@kamal thakur回复.

Swift 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)&param2=\(var2)"
request.httpBody = postString.data(using: .utf8)
Alamofire.request(request).responseJSON {
    response in
    // do whatever you want here
}

Swift相关问答推荐

为什么Swift在某些链调用中不能对不可变值使用变异成员,而在其他链调用中则不能使用变异成员?

如何在一个角色隔离类上编写自定义==实现?

从后台线程获取@发布属性的值(不更改它)是正确的吗?

有条件地在同一视图上设置两个不同的过渡

当模式以编程方式关闭时在父视图控制器中触发操作

类型擦除`AsyncMapSequence, Element>`

将弱引用作为类函数引用传递时,弱引用无法按预期工作

如何从 Swift 中隐藏 Objective-C 类接口的一部分?

MainActor 隔离可变存储属性为何会出现可发送错误?

将基于MyProtocol的泛型函数的参数更改为使用存在的any MyProtocol或some MyProtocol是否会受到惩罚?

符合协议 - 错误?

您可以在运行时访问 Picker 元素并更改它们的 colored颜色 吗

Subclass.fetchRequest() Swift 3.0,扩展并没有真正帮助 100%?

subscribeOn 和 observeOn 的顺序重要吗?

调整文本的字体大小以适应 UIButton

如何使用 swift 将 Images.xcassets 中的图像加载到 UIImage 中

如何在 Swift 中将 NSURL 转换为字符串

更改在变量的 willSet 块中设置的值

如何判断 firebase 数据库值是否存在?

枚举大小写的原始值必须是文字