简体   繁体   English

Swift - 等待委托 function 完成完成处理程序

[英]Swift - Wait for a delegate function to finish a completion handler

Suppose I have a function with completion handler and my AppDelegate extends from any notification delegate like this:假设我有一个带有完成处理程序的 function 并且我的 AppDelegate 从任何通知委托扩展,如下所示:

var flag = false
class AppDelegate: finishWorkingDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
    }

    private func updateData(completion: () -> Void) {
        //wait for delegate
        completion()
    }
    
    //delegate function
    func finishWorking(workComplete: Bool) {
        flag = true
    }
}

So my updateData function needs to wait until finishWorking delegate method where called to launch completion.所以我的updateData function 需要等到调用完成的完成委托方法才能启动完成。

finishWorking is triggered when a background task did finish at any time.当后台任务在任何时候完成时触发finishWorking

updateData can be used some where at any moment, like: updateData可以随时在某些地方使用,例如:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    updateData() {
        //do some other work
    }
}

I used a loop for wait until flag changes to true to launch completion我使用循环等待标志更改为true以启动完成

func updateData(completion: () -> Void) {
    while !flag {
        //...
    }
    completion()
}

But this method freezes the app.但是这种方法会冻结应用程序。 So, there is a better solution?那么,有更好的解决方案吗?

PD: I know that I can use the delegate function to do "some other work" but this is a particular case, I made this example code to explain the problem as clear as possible. PD:我知道我可以使用委托 function 来做“一些其他工作”,但这是一个特殊情况,我制作了这个示例代码以尽可能清楚地解释问题。 It needs to be as described.它需要如所描述的那样。

Whatever the work you do in finishWorking you shouldn't freeze the app, let the app opens the initial vc and show an activity/loading until the heavy work is done then refresh that vc无论您在完成工作中所做的工作finishWorking应冻结应用程序,让应用程序打开初始 vc 并显示活动/加载,直到完成繁重的工作然后刷新该 vc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM