Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dispatch_time_t with NSTimeInterval

Tags:

ios

swift

I have an NSTimeInterval value, I need to create a dispatch_time_t value with it. This is what I tried:

let timeInterval : NSTimeInterval = getTimeInterval()

//ERROR: Binary operator '*' cannot be applied to operands of type 'NSTimeInterval' and 'UInt64'
let dispatch_time = dispatch_time(DISPATCH_TIME_NOW, Int64(timerInterval * NSEC_PER_SEC))

I understand this error message, but I don't know how to get rid of it. Could someone please provide some suggestions? How can I create a dispatch_time instance with NSTimeInterval? Thanks!

like image 979
Leem.fin Avatar asked Sep 09 '15 12:09

Leem.fin


3 Answers

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.

like image 154
whyceewhite Avatar answered Sep 20 '22 19:09

whyceewhite


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)))
like image 12
Shardul Avatar answered Sep 21 '22 19:09

Shardul


Alternatively:

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

like image 3
Matthew Avatar answered Sep 21 '22 19:09

Matthew