xcode Alamofire 错误域=NSURLErrorDomain 代码=-999“已取消”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40447436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alamofire Error Domain=NSURLErrorDomain Code=-999 "cancelled"
提问by Kenny H
I already have successfully got keychain for my token and passing it to AccessTokenAdapter class shown below. http127.0.0.1:8000/api2/projects/?format=json is passed as projectsURL.
我已经成功获得了令牌的钥匙串并将其传递给如下所示的 AccessTokenAdapter 类。http127.0.0.1:8000/api2/projects/?format=json 作为projectsURL 传递。
class AccessTokenAdapter: RequestAdapter {
private let accessToken: String
init(accessToken: String) {
self.accessToken = accessToken
}
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
// print("JWT \(accessToken)")
urlRequest.setValue("JWT \(accessToken)", forHTTPHeaderField: "Authorization")
return urlRequest
}
}
let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: self.keychain["token"]!)
sessionManager.request(self.projectsURL, method: .get, encoding: JSONEncoding.default).responseJSON{ response in
switch response.result {
case .success:
print("yey I made it")
case .failure(let error):
print(error)
}
}
however, from print(error), my Xcode shows error like Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=http://127.0.0.1:8000/api2/projects/?format=json, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=http127.0.0.1:8000/api2/projects/?format=json}
但是,从打印(错误),我的 Xcode 显示错误,如 Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey= http://127.0.0.1:8000/api2/projects/?format=json, NSLocalizedDescription=取消,NSErrorFailingURLStringKey=http127.0.0.1:8000/api2/projects/?format=json}
Any ideas?
Alamofire 4.0
Keychain
Xcode 8.1
Swift3
Using JWT for authentication
Using Postman with header, key = "Authentication", value = "JWT (token generated here)" works fine
有任何想法吗?
Alamofire 4.0
Keychain
Xcode 8.1
Swift3
Using JWT for authentication
Using Postman with header, key = "Authentication", value = "JWT (token generated here)" 工作正常
回答by Vitalii
When you make sessionManager a let constant it won't live longer than the embracing it function, thus the session ends as soon as the manager is deallocated.
当您将 sessionManager 设为 let 常量时,它的寿命不会超过拥抱它的功能,因此一旦管理器被释放,会话就会结束。
To fix this, make sessionManager live longer. For example in my case I made it a class property:
要解决此问题,请延长 sessionManager 的寿命。例如,在我的情况下,我将其设为类属性:
class NetworkRequest: {
var sessionManager = Alamofire.SessionManager()
...
func performRequest(_ call: APICall, customLink: String = "", parameters: Dictionary<String, Any> = ["":"" as Any]) {
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = call.suggestedTimeout()
sessionConfig.timeoutIntervalForResource = call.suggestedTimeout()
sessionManager = Alamofire.SessionManager(configuration: sessionConfig)
sessionManager.adapter = AccessTokenAdapter()
sessionManager.request(urlString,
method: call.method(),
parameters: parameters,
encoding: call.chooseEncoding(),
headers: [:])
.responseJSON
{ response in
...
}
}
}
The solution might be different according to your situation, but the idea is to keep sessionManager alive until the network request ends.
根据您的情况,解决方案可能会有所不同,但其想法是让 sessionManager 保持活动状态,直到网络请求结束。
回答by Rajukumar Patel
self.getSessionManager()
.request(urlstring,
method: methods,
parameters: parameters,
encoding: JSONEncoding.prettyPrinted,
headers: Header
).responseJSON(
queue: nil,
options: JSONSerialization.ReadingOptions.allowFragments
) { (responseObject) in
// response parsing code is here
}.session.finishTasksAndInvalidate()
Just put the method of invalidate after task finish, means session.finishTasksAndInvalidate()
把任务完成后invalidate的方法就行了,意思是 session.finishTasksAndInvalidate()
All works great.
一切都很好。
回答by Kenny H
Just solved. Looks like it's required to set httpmethod beforehand.
刚解决。看起来需要事先设置httpmethod。
let url = URL(string: "http://127.0.0.1:8000/api2/projects/?format=json")
var urlRequest = URLRequest(url:url!)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue("JWT \(self.keychain["token"]!)", forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest)
.responseJSON { response in
debugPrint(response)
}
回答by Micah Montoya
In case other run into this as well as I did and it wasn't a https issue or other answer given in the many other SO posts that I found, I was getting this and found the cause to be a controller that was making a request but the controller was not to be shown. Kind of like if you have some controller that appears only on specific conditional and it, itself makes a request which is done in the viewWillAppear or other. I used a base class that determines if the call in the conditional controller should attempt the request or not. This fixed the problem for me.
如果其他人和我一样遇到这个问题,并且这不是我发现的许多其他 SO 帖子中给出的 https 问题或其他答案,我得到了这个并发现原因是发出请求的控制器但控制器不显示。有点像如果您有一些仅在特定条件下出现的控制器,它本身会发出一个在 viewWillAppear 或其他中完成的请求。我使用了一个基类来确定条件控制器中的调用是否应该尝试请求。这为我解决了问题。
回答by Luan Si Ho
This error usually caused by the SessionManager you created falling out of scope and being deinited, and your requests will be cancelled. Keep a reference to it, my solution is using a variable to store SessionManager in your APIService class
此错误通常是由您创建的 SessionManager 超出范围并被取消引起的,您的请求将被取消。保留对它的引用,我的解决方案是使用变量将 SessionManager 存储在您的 APIService 类中
public lazy var sharedManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 60
configuration.timeoutIntervalForResource = 60
let manager = Alamofire.SessionManager(configuration: configuration)
return manager
}()