【问题标题】:Alamofire Request error: NSURLErrorDomain Code -1005 The network connection was lostAlamofire 请求错误:NSURLErrorDomain Code -1005 网络连接丢失
【发布时间】:2016-02-22 07:36:39
【问题描述】:

我正在将我的项目从 AFNetworking 转移到 Alamofire。真的很喜欢这个项目。但是,我在尝试发出 GET 请求时收到此错误。

下面是一些示例代码:

class func listCloudCredntials(onlyNew onlyNew: Bool = true, includePending: Bool = true) -> Request {

    let parameters: [String: AnyObject] = includePending ? ["include_pending": "true"] : [:]

    let urlString = "https://myapp-staging.herokuapp.com/api/1/credntials"

    let token = SSKeychain.storedToken()

    let headers: [String: String] = ["Authorization": "Bearer \(token)"]

    return Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON, headers: headers)
}

然后,在我的 VC 中:

listCloudCredntials().validate().responseJSON() {
    (response: Response<AnyObject, NSError>) in

    switch response.result {
    case .Success(let result):
        printCR("success: \(result)")

    case .Failure(let error):
        printCR("error: \(error)")
    }
}

这是我遇到的错误:

Error Domain=NSURLErrorDomain Code=-1005 "网络连接是 丢失。” UserInfo={NSUnderlyingError=0x14e9c77f0 {错误 域=kCFErrorDomainCFNetwork 代码=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://myapp-staging.herokuapp.com/api/1/credntials, NSErrorFailingURLKey=https://myapp-staging.herokuapp.com/api/1/credntials, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=网络连接丢失。}

我尝试在 iOS 模拟器上运行 1OS 8.4 和 iOS 9.1,以及运行 iOS 9.1 的 iPhone 6S。

我做错了什么?

--------编辑--------

澄清一下,这个函数在 AFNetworking 上工作得很好。

这是 debugprint(request) 结果(这是一个 GET 请求):

$ curl -i \
-H "Authorization: Bearer some-JWT-Security-Token" \
-H "Content-Type: application/json" \
-H "Accept-Language: en-US;q=1.0" \
-H "Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
-H "User-Agent: Company/com.Company.AppName (1081; OS Version 9.2 (Build 13C75))" \
-d "{\"include_pending\":\"true\"}" \
"https://appname-staging.herokuapp.com/api/1/credntials"

我必须将 curl -i 更改为 curl -X GET 才能使 curl 成功返回。

这是我需要在应用程序中正常运行的另一个调用。

curl -i \
-X POST \
-H "Content-Type: application/json" \
-H "Accept-Language: en-US;q=1.0" \
-H "Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
-H "User-Agent: Company/com.Company.AppName (1081; OS Version 9.2 (Build 13C75))" \
-d "{\"token\":\"UserSessionTokenString\"}" \
"https://appname-staging.herokuapp.com/api/1/authenticate/user"

可能是 GET 与 POST 的区别吗?

【问题讨论】:

标签: ios xcode swift rest alamofire


【解决方案1】:

解决了!我对 GET 请求使用 JSON 编码。这是答案:Alamofire Request error only on GET requests

【讨论】:

    【解决方案2】:

    如果你将请求保留在你的vc或其他对象中,这个错误就会消失。

    【讨论】:

    • 不正确,我刚试了下,失败了。请参阅上面的更新代码。
    猜你喜欢
    • 2015-07-27
    • 2019-10-12
    • 2023-03-10
    • 2017-11-06
    • 2014-10-11
    • 2017-05-07
    • 2014-09-03
    • 2017-03-08
    • 1970-01-01
    相关资源
    最近更新 更多