swift - 处理 JSON 分页,并将数据添加到 TableView ?

标签 swift realm swift4 objectmapper moya

我收到格式为 JSON 的响应:

{
    "current_page":1,
    "data":[
        {
            "id":1,
            "title":"Title 1"
        },
        {
            "id":2,
            "title":"Title 2"
        },
        {
            "id":3,
            "title":"Title 3"
        }
    ]
}

如您所见,data 包含对象列表,在本例中为 Post 列表。这是我的 Realm/Objectmapper Post 类:

import RealmSwift
import ObjectMapper

class Post: Object, Mappable {
    let id = RealmOptional<Int>()
    @objc dynamic var title: String? = nil

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

    func mapping(map: Map) {

    }
}

我创建了一个通用类(我不确定它是否写对了)来处理 Pagination 响应。我希望它是通用的,因为我有其他分页响应返回 User 而不是 Post 以及其他对象。

这是我当前的 Pagination 类:

import ObjectMapper

class Pagination<T: Mappable>: Mappable {
    var data: [T]?

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

    func mapping(map: Map) {
        data <- map["data"]
    }
}

但是,我不确定我是否正确地编写了这个类。

这是我调用发送回分页数据的端点的类(我删除了不相关的代码):

var posts = [Post]()

provider.request(.getPosts(page: 1)) { result in
    switch result {
    case let .success(response):
        do {
            let json = try JSONSerialization.jsonObject(with: response.data, options: .allowFragments)

            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // Not sure what to do here to handle and retrieve the list of Posts
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            // Eventually, I need to append the posts to the variable
            // self.posts.append(pagination.data)

            // Reload the table view's data
            self.tableView.reloadData()
        } catch {
            print(error)
        }
    case let .failure(error):
        print(error)
        break
    }
}

如何正确处理 JSON 响应以获取 Post 列表,然后将它们附加到 var posts = [Post]() 变量?我是否需要对我的 Pagination 类进行任何更改?

最佳答案

一旦有了 json,就可以很容易地使用对象映射器解析它:

let pagination = Mapper<Pagination<Post>>().map(JSONObject: json)

还可以进一步推广,我用直接引用作为例子。您的 Pagination 类也可以保存当前页面索引值。

我认为您还缺少 Post 类中 mapping(map:) 函数的实现,它应该是这样的:

func mapping(map: Map) {
    title <- map["title"]
}

关于swift - 处理 JSON 分页,并将数据添加到 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736050/

相关文章:

ios - 从 AppDelegate 显示两个 ViewController

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - Firebase电子邮件身份验证系统登录任意帐户:

ios - RLMIt 的大小是多少?

ios - 存储可解码到 Realm 但数组始终为空

ios - 如何在 swift 4 中比较两个 CGColor

swift - 具有原始值的枚举

swift - Realm 通知不会触发初始值

ios11 - 无法自动更新约束

swift - 合并两个元组数组