0

我正在使用 alamofire,getPrescriptions当用户打开应用程序时发出请求(),该应用程序是一个带有 completionHandler 的块。该函数从 ws 检索列表并且可以分页,但我不知道端点有多少项目..所以我做了类似的事情:

 //todo: temp? pagination
        if prescriptions.count == 10 {
            getPrescriptions(page: page!+1, completionHandler: { (_) in
                    print("get prescription page", page!+1)
                completionHandler(prescriptions)
            })
        } else {
            completionHandler(prescriptions)
        }

我已经做了临时的,但我不知道我怎么能做得更好。流程是这样的: session.getPrescriptions(completion) 并且getPrescriptions可以在需要时调用自己。

这是完整的代码:

 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

    })


}
4

0 回答 0