首页 > 解决方案 > 无法使用 Alamofire 从这个 swift 类访问我的 API

问题描述

我正在尝试访问我在 Mac 上安装的 API。该 API 在此地址上运行良好https://localhost:5001/users/,当我使用浏览器运行时,它会加载所有内容,当我尝试使用以下代码加载它时:

class ConnectorManager: NSObject {
    open class MyServerTrustPolicyManager: ServerTrustPolicyManager {
        open override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
            return ServerTrustPolicy.disableEvaluation
        }
    }

    let sessionManager = SessionManager(delegate:SessionDelegate(), serverTrustPolicyManager:MyServerTrustPolicyManager(policies: [:]))

    func getAllUsers() {
        let userUrl = ConnectorStatics.URL_BASE + ConnectorStatics.URL_USR
        sessionManager.request(userUrl, method: .get, encoding: JSONEncoding.default).responseJSON { response in
            if response.result.isSuccess {
                if let data = response.result.value {
                    if (data as? [[String : AnyObject]]) != nil {
                        print("data_1: \(data)")
                    }
                }
            } else {
                print("Unable to connect")
            }
        }
    }
}

Xcode 向我显示此错误:

2019-06-03 17:41:13.427145+0200 MyApp[73332:3683174] Task <25D82DBB-4754-4E5F-8A90-690BD0994323>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://localhost:5001/users/, NSErrorFailingURLKey=https://localhost:5001/users/, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <25D82DBB-4754-4E5F-8A90-690BD0994323>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <25D82DBB-4754-4E5F-8A90-690BD0994323>.<1>, NSLocalizedDescription=cancelled} [-999]
2019-06-03 17:41:13.429975+0200 MyApp[73332:3683156] Task <25D82DBB-4754-4E5F-8A90-690BD0994323>.<1> finished with error - code: -999
2019-06-03 17:41:13.431713+0200 MyApp[73332:3683154] Task <25D82DBB-4754-4E5F-8A90-690BD0994323>.<1> HTTP load failed (error code: -999 [1:89])

我的课怎么了?谁能帮我解决它?谢谢

标签: swiftalamofire

解决方案


对于有相同问题的每个人,我将发布解决方案:

private static var Manager : Alamofire.SessionManager = {
        // Create the server trust policies
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "localhost:5001": .disableEvaluation
        ]
        // Create custom manager
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
        let man = Alamofire.SessionManager(
            configuration: URLSessionConfiguration.default,
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
        )

        man.delegate.sessionDidReceiveChallenge = { session, challenge in
            var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
            var credential: URLCredential?

            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
                disposition = URLSession.AuthChallengeDisposition.useCredential
                credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            } else {
                if challenge.previousFailureCount > 0 {
                    disposition = .cancelAuthenticationChallenge
                } else {
                    credential = man.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

                    if credential != nil {
                        disposition = .useCredential
                    }
                }
            }

            return (disposition, credential)
        }

        return man
    }()

现在有了这个片段,应用程序可以正常工作


推荐阅读