在WatchOS上与Alamofire联网

时间:2018-09-19 11:23:07

标签: swift alamofire watchkit

我正在为WatchOS构建应用扩展程序,并且我想在Watch应用中执行一些URL请求。我在网络部分使用Alamofire。

每当我执行一个简单的请求时,我都会在模拟器以及真实设备上收到这些错误: load failed with error Error Domain=NSURLErrorDomain Code=-2000 "can’t load from network"

我不清楚为什么会这样。手表已与手机配对。 使用Charles Proxy,我可以看到请求不是通过网络发送的,因此在发送之前就失败了。

欢迎提出任何想法。

编辑 这是我的Communications类的工作摘录:

import Foundation
import Alamofire

class Communication {
    internal lazy var manager = Communication.getSessionManager()

    typealias SuccesBlock = (DataResponse<Any>?) -> ()
    typealias FailureBlock = (DataResponse<Any>?, Error) -> ()
    typealias ProgressBlock = (Progress) -> ()

    internal static var serverTrustPolicyManager: ServerTrustPolicyManager {
        get {
            return ServerTrustPolicyManager(policies: [:])
        }
    }

    static func getSessionManager(_ serializeRequest:Bool = false) -> Alamofire.SessionManager {
        let manager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default, delegate: Alamofire.SessionManager.default.delegate, serverTrustPolicyManager: serverTrustPolicyManager)
        return manager
    }

    static var httpHeaders: HTTPHeaders {
        get {
            var httpHeaders = HTTPHeaders()
            httpHeaders["Accept"] = "application/json"
            return httpHeaders
        }
    }

    func get(_ url: URL, parameters: [String: Any]?, success: @escaping SuccesBlock, failure: @escaping FailureBlock) {
        manager.request(url, method: HTTPMethod.get, parameters: parameters, encoding: URLEncoding.default, headers: Communication.httpHeaders).validate().responseJSON { [weak self] (response) in
            self?.handle(response, success: success, failure: failure)
        }
    }

    internal func handle(_ response: DataResponse<Any>, success: @escaping SuccesBlock, failure: @escaping FailureBlock) {
        switch response.result {
        case .success:
            DispatchQueue.main.async {
                success(response)
            }
        case .failure(let error):
            DispatchQueue.main.async {
                failure(response, error)
            }
        }
    }
}

我发送给get(_ url: URL, parameters: [String: Any]?, success: @escaping SuccesBlock, failure: @escaping FailureBlock)函数的所有内容都出现-2000错误。 .responseJSON代码块从不执行。

编辑2

我得到的完整错误如下:

`2018-09-20 12:12:48.006544+0100 My App Watch Extension[61347:2465172] Task <F80A9AD4-519B-424C-868A-8E239C949016>.<7> load failed with error Error Domain=NSURLErrorDomain Code=-2000 "can’t load from network" UserInfo={NSLocalizedDescription=can’t load from network, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <F80A9AD4-519B-424C-868A-8E239C949016>.<7>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <F80A9AD4-519B-424C-868A-8E239C949016>.<7>"
), NSErrorFailingURLStringKey=https://my.request.url, _kCFNetworkErrorConditionalRequestKey=<CFMutableURLRequest 0x78f37a70 [0x201628c]> {url = https://my.request.url, cs = 0x0}, _kCFNetworkErrorCachedResponseKey=<CFCachedURLResponse 0x7b3d7f20 [0x201628c]>, NSUnderlyingError=0x7b436380 {Error Domain=kCFErrorDomainCFNetwork Code=-2000 "(null)" UserInfo={_kCFNetworkErrorCachedResponseKey=<CFCachedURLResponse 0x7b3d7f20 [0x201628c]>, _kCFNetworkErrorConditionalRequestKey=<CFMutableURLRequest 0x78f37a70 [0x201628c]> {url = https://my.request.url, cs = 0x0}}}, NSErrorFailingURLKey=https://my.request.url} [-2000]`

在控制台中收到此错误后,我现在可以看到请求仍然发送并成功。我以为在看到此错误之后情况并非如此,但是现在我看到,经过一段时间的延迟后,请求按预期方式工作。

因此最终该应用程序将运行,但是仍然存在的问题是:为什么会出现此错误以及如何消除该错误?

1 个答案:

答案 0 :(得分:9)

错误描述是

  

NSURLErrorCannotLoadFromNetwork

     

当任务需要从网络加载时会发送此错误,但是“仅从缓存加载”指令阻止了此错误。

您可以通过设置Alamofire请求的requestCachePolicy来解决此问题,例如:

class RequestManager {

    let manager: SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
        return SessionManager(configuration: configuration)
    }()

    func fetch() {

       manager.request("https://www.bla.blub") 

       ...