swift - 在 WatchOS 上与 Alamofire 联网

标签 swift alamofire watchkit

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

每当我做一个简单的请求时,我在模拟器和真实设备上都会收到这些错误: 加载失败,错误 Error Domain=NSURLErrorDomain Code=-2000 “无法从网络加载”

我不清楚为什么会这样。 watch 与手机配对。 使用 Charles Proxy 我可以看到请求没有通过网络发送,所以它甚至在发送之前就失败了。

欢迎提出任何想法。

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

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]`

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

所以最终该应用程序将运行,但是,剩下的问题是:为什么会出现此错误以及如何消除它?

最佳答案

错误描述为

NSURLErrorCannotLoadFromNetwork

This error is sent when the task needs to load from the network, but is blocked from doing so by the “load only from cache” directive.

你可以通过设置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") 

       ...

关于swift - 在 WatchOS 上与 Alamofire 联网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52404748/

相关文章:

swift - 没有像右 View 那样向文本字段添加标签

swift - 无法使用带有 Swift 3.1 的 Postgres 适配器构建 Kitura 服务器

ios - 在 iOS 8.0 嵌入式框架中使用 Alamofire

ios - Apple Watch 收到通知,没有触觉反馈

ios - 在 Apple Watch 中不起作用的接口(interface) Controller 之间传递数据

ios - 按钮可以包含 Apple Watch 应用程序中的组吗?

ios - 为什么 UIImageView 在其内容模式为 .scaleAspectFill 时在纵向图片中超出其限制?

ios - iOS 10 中的 HLS && .m3u8

swift - Alamofire POST 请求 URL

ios - post 请求发送 [String : Any] and a body of type string 类型的参数