简体   繁体   English

Swift:异步方法进入while循环

[英]Swift: Async method into while loop

I want to use a async function inside a while loop but the function don't get enough time to finish and the while loop starts again and never ends. 我想在while循环中使用异步函数,但是函数没有足够的时间来完成,而while循环再次启动并且永远不会结束。 I should implement this problem with increment variable , but what is the solution? 我应该用增量变量来实现这个问题,但是解决方案是什么? thanks a lot. 非常感谢。
output loops between "Into repeat" - "Into function" 输入循环“进入重复” - “进入功能”

var condition = true
var userId = Int.random(1...1000)
repeat {
     print("Into repeat")
     checkId(userId, completionHandler: { (success:Bool) -> () in
     if success {
           condition = false
     } else {
           userId = Int.random(1...1000)
       }
}) } while condition


func checkId(userId:Int,completionHandler: (success:Bool) -> ()) -> () {
        print("Into function")
        let query = PFUser.query()
        query!.whereKey("userId", equalTo: userId)
        query!.findObjectsInBackgroundWithBlock({ (object:[PFObject]?, error:NSError?) -> Void in
            if object!.isEmpty {
                completionHandler(success:false)
            } else {
                completionHandler(success:true)
            }
        })
    }

You can do this with a recursive function. 您可以使用递归函数执行此操作。 I haven't tested this code but I think it could look a bit like this 我没有测试过这段代码,但我觉得它看起来有点像这样

func asyncRepeater(userId:Int, foundIdCompletion: (userId:Int)->()){
    checkId(userId, completionHandler: { (success:Bool) -> () in
        if success {
            foundIdCompletion(userId:userId)
        } else {
            asyncRepeater(userId:Int.random(1...1000), completionHandler:  completionHandler)
        }
    })
}

You should use dispatch_group 你应该使用dispatch_group

repeat {
     // define a dispatch_group
     let dispatchGroup = dispatch_group_create()
     dispatch_group_enter(dispatchGroup) // enter group
     print("Into repeat")
     checkId(userId, completionHandler: { (success:Bool) -> () in
         if success {
           condition = false
         } else {
           userId = Int.random(1...1000)
       }
    // leave group
    dispatch_group_leave(dispatchGroup)
     }) 
    // this line block while loop until the async task above completed
    dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
} while condition

See more at Apple document 请参阅Apple文档中的更多内容

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

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