【问题标题】:Swift: For loop to synchronous one by one until all function responseSwift:For循环一一同步,直到所有函数响应
【发布时间】:2020-06-11 08:27:25
【问题描述】:

我是 swift 新手,我正在尽力而为。

当它执行时我有主要功能appointmentCall(),作为响应,我可能会得到多个约会。然后我将appointmentId 传递给appointmentDetail 函数以获取更多详细信息。

我想要的只是如何将 For 循环设置为同步过程。意味着它不会执行下一个约会,直到第一次完成。目前它执行所有约会。

我需要一个一个约会执行所有功能,一旦完成执行下一个约会。

预约电话 -> AppoinmentDetail -> processDetail -> 已完成。

代码:

func appointmentCall(_ selectedDate:Date) {

        DataProvider.main.serviceGetAppointment(date: selectedDate, callback: {success, result in

            do{
                if(success){
                    print(result as! Data)
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(ResponseData.self, from: result! as! Data)
                    if let appointments = response.appointments {
                        self.appData = appointments.map { AppointmentDownloadModel(appointmentModel: $0)}
                    }
                    for eachApp in self.appData {

                        self.appointmentDetail(AppId: appId)
                    }


                    self.tableView.reloadData()
                    return true
                }else{
                    return false
                }
            }catch let error {
                DataProvider.main.token = nil
                print(error as Any)
                return false
            }
        })

    }

func appointmentDetail(AppId: Int){
        DataProvider.main.serviceGetAppointmentDetail(Id: AppId , callback: {success, result in
            do{
                if(success){
                    let decoder = JSONDecoder()
                    let resp = try decoder.decode(AppointmentDetail.self, from: result! as! Data)
                    self.AppDetailData = resp
                    self.processDetail(appId: AppId)
                    return true
                }else{
                    return false
                }
            }catch let error {

                print(error as Any)
                return false
            }
        })

    }



func processDetail(appId: Int) {
guard let detail = AppDetailData, AppDetailData?.appointmentId == appId else {
    return
}
for firmParam in (detail.sectionList ?? []) {
    for firmItem in firmParam.items! {
        if firmItem.actionParamData != nil {
        let str = firmItem.actionParamData
        let param = str?.components(separatedBy: ":")
        let final = param![1].replacingOccurrences(of: "}", with: "")
        let fmId = final.components(separatedBy: ",")
        let frmId = fmId[0]
        self.firmDetails(actionParamData: Int(frmId) ?? 0)
        }
        //pdf download
        if firmItem.actionType == 2 {
        if firmItem.actionUrl != nil {
        self.contentLength(link: firmItem.actionUrl!)

        let fileURL = URL(fileURLWithPath: firmItem.actionUrl ?? "")
        let fileTitle = firmItem.textField ?? ""
        self.downloadPDFTask(pdfURL: firmItem.actionUrl ?? "")

             }
            }

        }

    }
}

【问题讨论】:

  • 您可以使用递归函数调用另一个具有完成处理程序的函数,在该完成处理程序中再次调用该函数,并从成员变量列表中获取您的值,每次函数完成时它只是再次调用自己,您会知道它们只有在每个完成后才按顺序处理
  • @AngryDuck 你能举个例子吗?谢谢?因为appointmentDetail 已经在调用appointmentCall 函数。
  • 查看我对高级通用示例的回答

标签: ios swift asynchronous synchronization


【解决方案1】:

如果您使用带有完成处理程序的递归函数,它将确保您基本上可以遍历一个数组并调用一个函数来做某事,并在您对下一个值执行相同操作之前知道它已经完成。请参阅下面的高级通用示例

func doSomething()
{
    // Call this function with the first index in the array
    firstFunction(index: 0)

    // Now were here and we know that every value in the member variable array has been processed by "secondFunction"
}

func firstFunction(index: Int)
{
    let value = memberVariableArray[index]

    secondFunction(String: value) { (returnValueFromSecondFunction) in
        // do something with the return value from the second function

        // Recall this function with the next index (if we have another one)
        let newIndex = index + 1
        if newIndex < memberVariableArray.count
        {
            self.firstFunction(index: newIndex)
        }
    }
}

func secondFunction(valueToDoSomethingWith: String, completion: @escaping (String) -> Void)
{
    // Do something here

    // Complete function
    completion("The Value you want back")
}

【讨论】:

  • 谢谢。让我实现它并回复您。
  • 不用担心,我希望它有所帮助,抱歉,它不是特定于您的示例,但我目前正在处理其他内容,并且只有时间为此类设置提供一个通用示例!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2019-06-16
  • 2018-09-17
  • 1970-01-01
  • 2021-10-17
  • 2017-02-21
相关资源
最近更新 更多