Delay function in fast

I don’t have code for the sample or anything else because I have no idea how to do this, but can someone please tell me how to quickly defer a function with a given time?

+118
function ios swift delay
03 Mar. '15 at 0:03
source share
4 answers

You can use GCD (in the example with a delay of 10 seconds):

Swift 2:

let triggerTime = (Int64(NSEC_PER_SEC) * 10) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in self.functionToCall() }) 

Swift 3:

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: { self.functionToCall() }) 
+343
Mar 03 '15 at 0:13
source share

Swift 3 Version for a delay of 10 seconds

 unowned let unownedSelf = self let deadlineTime = DispatchTime.now() + .seconds(10) DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { unownedSelf.functionToCall() }) 
+28
Oct 15 '16 at 11:58
source share
  NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false) 

This will call functionHere () with a delay of 3 seconds

+24
Apr 19 '15 at 12:10
source share

To add an argument to the delay function.

Install the dictionary first, then add it as userInfo. Untie the information with a timer as an argument.

 let arg : Int = 42 let infoDict : [String : AnyObject] = ["argumentInt", arg] NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false) 

Then in the called function

 func functionHereWithArgument (timer : NSTimer) { if let userInfo = timer.userInfo as? Dictionary<String, AnyObject> { let argumentInt : Int = (userInfo[argumentInt] as! Int) } } 
+4
Feb 23 '16 at 0:32
source share



All Articles