在 MAC OS 应用程序中使用 Alamofire 库调用 API 时出现 "The network connection was lost." 错误

Getting "The network connection was lost." error when calling API using Alamofire library in MAC OS App

我已经为 API 调用集成了 Alamofire 库,但出现以下错误:

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=57, NSUnderlyingError=0x600000c68990 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask .<1>" ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=OUR_Server_URL, NSErrorFailingURLKey=OUR_Server_URL, _kCFStreamErrorDomainKey=1}

我也将以下 属性 添加到 .plist 文件中:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

我正在使用以下代码使用 Alamofire :-

Alamofire code :

func postFormDataWebService(methodType : HTTPMethod, contentType : String, url : String,
                                  parameters : NSMutableDictionary?,
                                  success: @escaping(_ response : NSDictionary, _ status : String) -> Void,
                                  failure: @escaping(_ error : Error, _ status : Int) -> Void){

    var headers : HTTPHeaders = [ "Content-Type": contentType, "accept": "application/json"]

    Alamofire.request(url, method: methodType, parameters:parameters as? [String : Any] , encoding: JSONEncoding.default, headers: headers)
        .responseJSON {
        (response:DataResponse) in
        var responseStatusCode: Int = 0
        switch response.result {

        case .success:
            responseStatusCode = (response.response?.statusCode)!
            let data = response.result.value as! NSDictionary
            print(data)
            success(data, data["status"] as? String ?? "")

            break
        case .failure(let error):
            responseStatusCode = response.response?.statusCode ?? 0
            print("statusCode :: ", response.response?.statusCode  ?? 0)
            print("Error :: ",error.localizedDescription)                
            failure(error,responseStatusCode)
        }
    }
}

API Calling function :

ApiManager.shared.postFormDataWebService(methodType: :POST, contentType: "application/json", url: LoginUrl, parameters: parameters, 
success: { (response, status) in
    print("response = \(response)")
    print("status = \(status)")
}) { (error, status) in
    print("Login Error == \(error)\nStatus == \(status)")
}

如有任何帮助,我们将不胜感激。

您只需在您的能力中启用此选项即可。

希望,这就是您要找的。有任何疑虑,请回复我。 :)