【问题标题】:Making sense of Realm, Moya, and ObjectMapper理解 Realm、Moya 和 ObjectMapper
【发布时间】:2018-12-23 05:06:22
【问题描述】:

所以我试图弄清楚如何使用 Realm、Moya 和 ObjectMapper。

我使用 Moya 向我的 API 发出请求。我使用 Realm 将返回的数据保存在本地数据库中。我使用 ObjectMapper 将 JSON 对象映射到正确的 Realm 变量。

但是,我现在遇到了一个问题,我不确定如何解码 JSON 响应以使其通过映射器。

这是我的 Moya 代码:

provider.request(.signIn(email: email, password: password)) { result in
    switch result {
    case let .success(response):
        do {
            // Get the response data
            let data = try JSONDecoder().decode(MyResponse.self, from: response.data)

            // Get the response status code
            let statusCode = response.statusCode

            // Check the status code
            if (statusCode == 200) {
                // Do stuff
            }
        } catch {
            print(error)
        }
    case let .failure(error):
        print(error)
        break
    }
}

错误发生在这一行:

In argument type 'MyResponse.Type', 'MyResponse' does not conform to expected type 'Decodable'

MyResponse 类如下所示:

class MyResponse: Object, Mappable {
    @objc dynamic var success = false
    @objc dynamic var data: MyResponseData? = nil

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {

    }
}

我明白为什么我遇到了这个错误,我只是不知道解决它的正确方法。我在上述框架之一的文档中遗漏了什么吗?我这样做完全错了吗?我应该如何修复我的代码行?


我尝试了@Kamran 的解决方案,但我得到了错误:

参数标签“(JSON:)”不匹配任何可用的重载

上线:

let myResponse = MyResponse(JSON: json)

【问题讨论】:

    标签: ios swift realm objectmapper moya


    【解决方案1】:

    您收到该错误是因为您正在使用 Swift JSONDecoder 进行解码,这需要您实现包含 Encodable 和 Decodable (JSON YourObject) 的 Codable。

    如果您使用的是 Swift 4,则可以使用 Codable 而不是依赖 3rd 方库。

    MyResponse 将变为:

    class MyResponse: Codable {
        let success: Bool
        let data: MyResponseData? 
    }
    

    MyResponseData 也应该实现 Codable。

    在这之后你应该能够做到:

    do {
        let data = try JSONDecoder().decode(MyResponse.self, from: response.data)
    } catch let error { 
        // handle error
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-12
      • 2016-03-28
      • 2017-04-27
      • 2019-03-18
      • 2018-03-18
      • 2016-02-21
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多