ios - Alamofire:[结果]:失败:错误域=NSURLErrorDomain 代码=-999 "cancelled"

标签 ios swift xcode alamofire

我要连接的服务使用的是自签名证书。 出于开发目的,我不想验证该链。

将 swift 3 与 Alamofire 4 结合使用。 相应地修复了 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>

连接和禁用评估的代码。

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

dumpPrint 的错误日志

[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=https://sub.url.com/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://sub.url.com/path}

URL 已被屏蔽。

最佳答案

要保留 SessionManager 实例,您需要在传递给 responseJSON 的闭包中捕获它:

sessionManager.request("https://sub.url.com/path", headers: headers).responseJSON { response in
    let _ = sessionManager // retain
    // ...
}

否则 sessionManager 很快就会被释放,它会超出范围并且任何正在执行的请求都会被取消。

关于ios - Alamofire:[结果]:失败:错误域=NSURLErrorDomain 代码=-999 "cancelled",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39984880/

相关文章:

ios - 使用 Parse 时出错 - "_OBJC_CLASS_$_ParseClientConfiguration",引用自 :

ios - Xcode 8 autolayout 毁了我的项目

ios - 快速滚动时自定义 UITableViewCell 更改字体

ios - 使用 'vendored_frameworks' 和 'source_files' 用于 cocoapod 使用 'use_frameworks!'

带有图像的 iOS 推送/本地通知,如 iMessage 中的图像

swift - 将 CABasicAnimation 添加到子类 UIButton - 如果启用

ios - 使用 Swift 编写 iOS 应用程序时在 iPhone 中获取奇怪的磁力计数据

swift - NSPageController 快速示例

xcode - 如何在 Xcode 4.6.2 中添加/修改捆绑加载器设置?

ios - swift 的部分 pagecurl 动画