如何在 Swift 中使用组合读取 JSON 错误对象的属性值? [英] How do I read the property values of a JSON error object using Combine in Swift?

查看:31
本文介绍了如何在 Swift 中使用组合读取 JSON 错误对象的属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所有的 API 端点都返回一个在 Postman 中看起来像这样的响应:

All of my API endpoints return a response which looks something like this in Postman:

{
    "statusCode": 401,
    "error": "Unauthorized",
    "message": "Missing authentication"
}

我想做的是发出请求,并在 Swift 中访问这些属性.在某些情况下,我会在应用程序的前面使用错误消息属性的值.这将由返回的 statusCode 确定.

What I would like to do is make the request, and have access to these properties in Swift. There will be some cases where I use the error message property's value in the front of the app. This will be determined by the statusCode returned.

我现在拥有的是:

    private var cancellable: AnyCancellable?
    let url = URL(string: "http://abc336699.com/create")
    self.cancellable = URLSession.shared.dataTaskPublisher(for: url!)
      .map { $0.data }

在此之前,我尝试过 tryMap,但它返回的错误类型并没有给我想要的灵活性.然后我继续尝试 Almofire,但对于我想做的事情来说,这似乎有点过头了.

Prior to this, I tried tryMap, but the type of error it returned didn't give me the flexibility I wanted. I then moved on and tried Almofire, but it seemed like an over kill for what I want to do.

我想检查收到的响应中返回的内容,但出现以下错误:

I wanted to check what is being returned in the response I get, but I get the following error:

Cannot assign value of type 'Publishers.Map<URLSession.DataTaskPublisher, Data>' to type 'AnyCancellable'

我想要简单地访问我的响应错误,以便我可以使用 combine 在整个应用程序中集成 API.

I want simple access to my response errors so I can integrate the API throughout the app using combine.

推荐答案

我不确定您将从何处获取数据,因为在 JSON 响应中没有数据密钥.在编写下面的代码之前,我的理解是您希望从提到的 JSON 响应中检查 errorstatusCode,然后继续您的业务逻辑.下面的代码是让您对我们如何做到这一点有一个模糊的概念.

I am not sure from where you will be getting your data as in JSON response there is no Key for data. Before writing below code my understanding was that you want to check error and statusCode from the mentioned JSON response and then move forward with your business logic. The below code is to give you a vague idea of how we can do that.

    enum CustomError: Error {

    case custom(_ error: String)
    case unknownStatusCode
    case errorOccurred
}

let url = URL(string: "http://abc336699.com/create")

    func load() -> AnyPublisher<Data,CustomError> {
    URLSession.shared.dataTaskPublisher(for: url!)
        .map(\.data)
        .tryMap { (data) -> Data in
            let genericModel = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]

            if let statusCode = genericModel?["statusCode"] as? String {
                switch statusCode {
                case "200":
                    guard let data = genericModel?["message"] as? Data else {
                        throw CustomError.custom("Parsing error")
                    }
                    return data
                default:
                    if let error = genericModel?["error"] as? String {
                        throw CustomError.custom(error)
                    } else {
                        throw CustomError.unknownError
                    }
                }
            }
            throw CustomError.errorOccurred
    }
    .decode(type: YourCustomDecodableModel.self, decoder: JSONDecoder())
    .mapError({ $0 as? CustomError ?? CustomError.errorOccurred })
    .eraseToAnyPublisher()
}

这篇关于如何在 Swift 中使用组合读取 JSON 错误对象的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆