I want to get the first 20 data for the first page from the url below. I want to get the next 20 data on the second page. I don't want to get all the data in the first time. I just want to get the first 20 data.
URL:
https://rss.itunes.apple.com/api/v1/us/books/top-free/all/%20100/non-explicit.json
JSON:
class BookProvider {
// MARK: - Properties
private let baseUrl = "https://rss.itunes.apple.com/api/v1"
// MARK: - Life Cycle
init() { }
// MARK: Functions
func loadTopCharts() -> Future<[Book], Error> {
let urlString = "us/books/top-free/all/100/non-explicit.json"
if let data = getData(from: urlString) {
if let songs = jsonDictionary(from: data)?["results"] {
do {
let data = try JSONSerialization.data(withJSONObject: songs, options: .fragmentsAllowed)
let bookDecoder = try JSONDecoder().decode([Book].self, from: data)
return Future { promixe in
promixe(.success(bookDecoder))
}
}catch {
debugPrint(error.localizedDescription)
}
}
}
return Future{ _ in }
}
private func getData(from urlString: String) -> Data? {
guard let url = URL(string: baseUrl + "/" + urlString) else {
fatalError("Couldn't load URL from provided string.")
}
do {
return try Data(contentsOf: url)
} catch {
debugPrint("Couldn't load data from URL:\n\(error)")
return nil
}
}
private func jsonDictionary(from data: Data) -> [String : Any]? {
do {
let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return (dictionary as? [String : Any])?["feed"] as? [String : Any]
}catch {
debugPrint(error.localizedDescription)
return nil
}
}
}