gpt4 book ai didi

swift3 - 对 Alamofire sessionmanager 感到困惑

转载 作者:行者123 更新时间:2023-12-02 08:51:54 27 4
gpt4 key购买 nike

使用 Alamofire 4.0 和 Swift 3.0 可以实现:

Alamofire.request("http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json", method: .get).responseJSON {
(response) -> Void in
print("Success: \(response.result)")
}

Success: SUCCESS

但是,当我尝试使用 Sessionmanager 以便包含超时间隔时,我的请求总是失败

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 15
let alamofireManager = Alamofire.SessionManager(configuration: configuration)
alamofireManager.request("http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json").validate().responseJSON {
response in
print("Success: \(response.result)")
print("Response String: \(response.result.value)")
}

Success: FAILURE

如果有人能帮助我指出正确的方向,我将不胜感激。

最佳答案

通过打印 response.result.error 我得到:

Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json}

这让我想到了这个reference :

You need to make sure that the manager is retained. 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.

解决方案:

解决您遇到的问题的一种方法是在类声明之外将自定义 session 管理器声明为全局变量,如下所示...

let sessionManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 15

return SessionManager(configuration: configuration)
}()

现在,您可以在类(class)中提出请求。

class ViewController: UIViewController {

let url = "http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json"

override func viewDidLoad() {
super.viewDidLoad()

sessionManager.request(url).validate().responseJSON { response in
switch response.result {
case .success:
print(response.result.value as! NSDictionary)
break

case .failure:
print(response.result.error!)
break
}
}
}

}

这会给你你正在寻找的东西。希望有帮助!

关于swift3 - 对 Alamofire sessionmanager 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com