【问题标题】:Nested callback function not working properly swift嵌套回调函数不能正常工作 swift
【发布时间】:2025-12-17 06:05:01
【问题描述】:

我正在尝试实现嵌套的完成处理程序,但由于某种原因,我的第二个处理程序在完成时没有触发。代码是这样的

//User presses a button on a cell. Code is in `cellForRowAtIndex...`
 cell.callback = {
            print("in CFRAIP")
            self.showPopUpDialog(completionHandler: { () -> Void in 
                print("AfterPOPUPDIALOG")
                self.requestBookingWithCompletionHandler(fetchBookingForDate: self.currentDate, row: indexPath.row)
            })
        }


func showPopUpDialog(completionHandler: () -> Void ){

    print("In show PopUPdialog")

    let alertController = UIAlertController(title: "Uppgifter", message: "Skriv in namn och telefonnummer", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Boka", style: .default) { (_) in

        //getting the input values from user
        self.bokadNamn = (alertController.textFields?[0].text)!
        self.bokadTelefon = (alertController.textFields?[1].text)!

        print("pressed ok in popup")
    }

    let cancelAction = UIAlertAction(title: "Avbryt", style: .cancel) { (_) in}

    //adding textfields to our dialog box
    alertController.addTextField { (textField) in
    textField.placeholder = "Namn"
    textField.layer.cornerRadius = 5
    }
    alertController.addTextField { (textField) in
    textField.placeholder = "Telefonnummer"
    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    //finally presenting the dialog box
    self.present(alertController, animated: true, completion: nil)
}

这是我得到的照片:

in CFRAIP
In show PopUPdialog
pressed ok in popup

print("AfterPOPUPDIALOG") 没有被触发,并且在用户在PopUP 中按下确定后,我的网络请求也没有运行。我觉得我错过了一些非常简单的东西,但不幸的是,我看不见它......

【问题讨论】:

    标签: swift completionhandler


    【解决方案1】:

    在函数func showPopUpDialog(completionHandler: () -> Void ) { 内部,您不会在任何地方调用完成处理程序completionHandler

    如果不调用完成处理程序,打印语句print("AfterPOPUPDIALOG") 将如何执行?

    在适当的地方调用您的完成处理程序completionHandler

    【讨论】:

    • 哇..哈哈我真的太累了。谢谢