无法使用Alamofire从此swift类访问我的API

时间:2019-06-03 15:45:23

标签: swift alamofire

我正在尝试访问我在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])

我班上怎么了?谁能帮我修复它?谢谢

1 个答案:

答案 0 :(得分:0)

对于遇到相同问题的每个人,我都会发布解决方案:

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

现在使用此代码段,该应用程序可以正常运行