I'm working with alamofire and I make a request (getPrescriptions
) when users open the app which is a block with a completionHandler. That function retrieves a list from ws and can be paginated, but I don't know how many items I have at the endpoint.. So I do something like:
//todo: temp? pagination
if prescriptions.count == 10 {
getPrescriptions(page: page!+1, completionHandler: { (_) in
print("get prescription page", page!+1)
completionHandler(prescriptions)
})
} else {
completionHandler(prescriptions)
}
I've made that temporary, but I can't figure out how could I do this better. The flow is like that: session.getPrescriptions(completion) and getPrescriptions
can call himself if needed.
here is the full code:
static func getPrescriptions(page: Int? = 1, completionHandler: @escaping (_ prescriptions: [Prescription]?) -> Void){
let endPoint = "/prescriptions?page=\(page!)&size=10"
doDefaultRequestWith(endPoint: endPoint, requestType: .get, completionWithError: { (error) in
return completionHandler(nil)
}, completionWithResponse: { (response) in
guard let prescriptionsArray = response.result.value as? NSArray else {
return
}
var prescriptions: [Prescription] = []
for prescriptionJSON in prescriptionsArray {
if let json = prescriptionJSON as? [String: AnyObject] {
if let prescription = Prescription(JSON: json) {
if let address = prescription.address {
session.setAddress(address)
}
prescriptions.append(prescription)
}
}
}
if prescriptions.count > 0 {
session.setPrescriptions(prescriptions: prescriptions)
} else {
completionHandler(nil)
}
//todo: temp? pagination
if prescriptions.count == 10 {
getPrescriptions(page: page!+1, completionHandler: { (_) in
print("get prescription page", page!+1)
completionHandler(prescriptions)
})
} else {
completionHandler(prescriptions)
}
}, completionWithJSON: { (_) in
})
}