Swift:异步方法进入while循环

时间:2015-10-28 01:22:55

标签: swift asynchronous

我想在while循环中使用异步函数,但是函数没有足够的时间来完成,而while循环再次启动并且永远不会结束。 我应该用增量变量来实现这个问题,但是解决方案是什么?非常感谢。
输入循环“进入重复” - “进入功能”

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)
            }
        })
    }

2 个答案:

答案 0 :(得分:17)

您可以使用递归函数执行此操作。我没有测试过这段代码,但我觉得它看起来有点像这样

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)
        }
    })
}

答案 1 :(得分:5)

您应该使用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

Apple document

了解详情