如何向DispatchQueue添加时间延迟变量

时间:2018-01-03 03:42:33

标签: ios swift grand-central-dispatch

首先,我使用arc4random

创建了一个randomDelay值

然后我想将randomDelay值添加到DispatchQueue以创建随机时间延迟变量

这是我的代码:

func animation1() {

UIView.animate(withDuration: 1, animations: {

    // various code

}, completion: { (true) in

    //delay calling the function by the randomDelay value of '0' to '2' seconds
    let randomDelay = arc4random_uniform(3)
    DispatchQueue.main.asyncAfter(deadline: .now() + randomDelay) { // the randomDelay value throws an unresolved identifier 'randomDelay' error
        self.showAnimation2() // Go to the next function
    }
  })
}

由于

3 个答案:

答案 0 :(得分:1)

我认为这会对你有帮助!

let aRandomVar = 2   // change 2 to desired number of seconds
 let when = DispatchTime.now() + Double(aRandomVar)
    DispatchQueue.main.asyncAfter(deadline: when) {
       // Your code with delay
    }

答案 1 :(得分:1)

您需要将 <?php use App\blacklist; $userName = $user->Name; $userName = strtoupper($userName); //dd(userName) --> return Tom, originally was Tom $blacklist = blacklist::select('blacklist_name')->get(); //dd($blacklist) --> return TOM if($contains = str_contains($userName, [$blacklist])){ echo "This person is blacklisted"; } ?> 投射到randomDelay。然后你按如下方式使用它:

Double

答案 2 :(得分:1)

你没有提到随机数的时间单位。我建议你选择一个单位。例如,秒:

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(Int(randomDelay)), execute: {...})

或毫秒:

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(randomDelay)), execute: {...})