I'm getting a JSON response of the format:
{
"current_page":1,
"data":[
{
"id":1,
"title":"Title 1"
},
{
"id":2,
"title":"Title 2"
},
{
"id":3,
"title":"Title 3"
}
]
}
As you can see, data
contains a list of objects, in this case, a list of Post
s. Here is my Realm/Objectmapper Post
class:
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) {
}
}
I created a generic class (I'm not sure it's written right) to handle Pagination
responses. I want it to be generic because I have other pagination responses that return User
s instead of Post
s, among other objects.
Here is my current Pagination
class:
import ObjectMapper
class Pagination<T: Mappable>: Mappable {
var data: [T]?
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
data <- map["data"]
}
}
However, I'm not sure if I've written this class right.
And here is the class where I call the endpoint that sends back the pagination data (I've removed irrelevant code):
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
}
}
How do I handle the JSON response correctly in order to get the list of Post
s and then append them to the var posts = [Post]()
variable? Do I need to make any changes to my Pagination
class?