xcode Alamofire:[结果]:失败:错误域=NSURLErrorDomain 代码=-999“已取消”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39984880/
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: [Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled"
提问by Sami M'Barek
The service I'm connecting to is using a self signed certificate. For dev purposes I do not want to validate that chain.
我要连接的服务正在使用自签名证书。出于开发目的,我不想验证该链。
Using swift 3 with Alamofire 4. Fixed the ATS accordingly:
在 Alamofire 4 中使用 swift 3。相应地修复了 ATS:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>url.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
Code to connect and disable evaluation.
用于连接和禁用评估的代码。
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"example.domain.com": .pinCertificates(
certificates: ServerTrustPolicy.certificates(),
validateCertificateChain: false,
validateHost: true
),
"sub.url.com": .disableEvaluation
]
let sessionManager = Alamofire.SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
let headers = ["Authorization": "Basic /*...*/"]
sessionManager.request("https://sub.url.com/path", headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
debugPrint(response)
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Error log from dumpPrint
来自 dumpPrint 的错误日志
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=https://sub.url.com/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://sub.url.com/path}
[结果]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey= https://sub.url.com/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey= https://sub.url.com/路径}
URL has been masked.
网址已被屏蔽。
回答by mixel
To retain SessionManagerinstance you need to capture it in closure passed to responseJSON:
要保留SessionManager实例,您需要在传递给的闭包中捕获它responseJSON:
sessionManager.request("https://sub.url.com/path", headers: headers).responseJSON { response in
let _ = sessionManager // retain
// ...
}
Otherwise sessionManageris deallocated shortly it goes out of scope and any executing requests are cancelled.
否则sessionManager很快就会被释放,它会超出范围并且任何正在执行的请求都会被取消。
回答by Jatin Nandwani
Please add this statement to the end of responseJson block:
请将此语句添加到 responseJson 块的末尾:
manager.session.invalidateAndCancel()
It happens if the object of the manager is not retained till execution of the block completes, so this would ensure its retention.
如果管理器的对象直到块的执行完成才保留,就会发生这种情况,因此这将确保其保留。
Cheers!
干杯!
回答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 ... .... }.session.finishTasksAndInvalidate()
Just put the method of invalidate after task finish, means session.finishTasksAndInvalidate()
把任务完成后invalidate的方法就行了,意思是 session.finishTasksAndInvalidate()
回答by john7ric
Please check in sessiondidReceiveChallenge:delegate implementation of NSURLSession. Chances are NSURLSessionAuthChallengeCancelAuthenticationChallengeis getting executed somewhere.
请检查sessiondidReceiveChallenge:委托执行的NSURLSession。有NSURLSessionAuthChallengeCancelAuthenticationChallenge可能在某处被处决。
回答by Jon Shier
You need to properly manage the lifetime of your SessionManagerinstance. Most commonly this is done by making a singleton instance. Otherwise, when your manager goes out of scope and is deinited, all outstanding requests will be cancelled.
您需要正确管理SessionManager实例的生命周期。最常见的是,这是通过制作单例实例来完成的。否则,当您的经理超出范围并被deinited 时,所有未完成的请求都将被取消。

