【发布时间】: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