Create dispatch_time_t with NSTimeInterval

let delayTime = dispatch_time(DISPATCH_TIME_NOW,
    Int64(0.3 * Double(NSEC_PER_SEC)))

dispatch_after(delayTime, dispatch_get_main_queue()) {
    //... Code
}

You can try this, this works fine with me.

In your code just replace your last line with:

let d_time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeInterval * Double(NSEC_PER_SEC)))

You have:

let timeInterval : NSTimeInterval = getTimeInterval()

let dispatch_time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeInterval * NSEC_PER_SEC))

And you are receiving the following error:

ERROR: Binary operator '*' cannot be applied to operands
of type 'NSTimeInterval' and 'UInt64'

As a result, you will need to cast or change the variables types in your Int64(timeInterval * NSEC_PER_SEC) equation so that they have compatible data types.

  • timeInterval is a NSTimeInterval which is an alias of type Double
  • NSEC_PER_SEC is an UInt64
  • The dispatch_time function is expecting an Int64 argument

Therefore, the error will go away by changing the NSEC_PER_SEC to a Double so that it matches the data type of timeInterval.

let dispatch_time = dispatch_time(DISPATCH_TIME_NOW,
    Int64(timeInterval * Double(NSEC_PER_SEC)))

Another random point: you will likely get a Variable used within its own initial value error when you name your variable dispatch_time when calling dispatch_time.


Alternatively:

let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5)

Tags:

Ios

Swift