Delay using DispatchTime.now() + float?
DispatchTime.now()
is a double. You cannot add a float and a double value together. (A small explanation about why can't you add values with different types can be found here).
Replace
var time: Float = 2.2
with
var time: Double = 2.2
And it will work fine.
How to Add a Time Delay Variable to DispatchQueue
You need to cast randomDelay
to a Double
. Then you use it as follows:
let randomDelay = arc4random_uniform(3)
DispatchQueue.main.asyncAfter(deadline: .now() + Double(randomDelay)) {
}
Binary operator '+' cannot be applied to operands of type 'DispatchTime' and 'Int32'
You could do this:
let x: Int32 = 2
let when = (DispatchTime.now().uptimeNanoseconds + (5 * UInt64(x)))
The problem is that you can not sum different types. And DispatchTime is represented using 64 bits (unsigned) so you can cast it using UInt64(x)
.
To get the UInt64
from DispatchTime you can use uptimeNanoseconds
or rawValue
How do I write dispatch_after GCD in Swift 3, 4, and 5?
The syntax is simply:
// to run something in 0.1 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your code here
}
Note, the above syntax of adding seconds
as a Double
seems to be a source of confusion (esp since we were accustomed to adding nsec). That "add seconds as Double
" syntax works because deadline
is a DispatchTime
and, behind the scenes, there is a +
operator that will take a Double
and add that many seconds to the DispatchTime
:
public func +(time: DispatchTime, seconds: Double) -> DispatchTime
But, if you really want to add an integer number of msec, μs, or nsec to the DispatchTime
, you can also add a DispatchTimeInterval
to a DispatchTime
. That means you can do:
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
os_log("500 msec seconds later")
}
DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(1_000_000)) {
os_log("1m μs seconds later")
}
DispatchQueue.main.asyncAfter(deadline: .now() + .nanoseconds(1_500_000_000)) {
os_log("1.5b nsec seconds later")
}
These all seamlessly work because of this separate overload method for the +
operator in the DispatchTime
class.
public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime
It was asked how one goes about canceling a dispatched task. To do this, use DispatchWorkItem
. For example, this starts a task that will fire in five seconds, or if the view controller is dismissed and deallocated, its deinit
will cancel the task:
class ViewController: UIViewController {
private var item: DispatchWorkItem?
override func viewDidLoad() {
super.viewDidLoad()
item = DispatchWorkItem { [weak self] in
self?.doSomething()
self?.item = nil
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: item!)
}
deinit {
item?.cancel()
}
func doSomething() { ... }
}
Note the use of the [weak self]
capture list in the DispatchWorkItem
. This is essential to avoid a strong reference cycle. Also note that this does not do a preemptive cancelation, but rather just stops the task from starting if it hasn’t already. But if it has already started by the time it encounters the cancel()
call, the block will finish its execution (unless you’re manually checking isCancelled
inside the block).
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)))
Wait/Delay in Xcode (Swift)
You only have to write this code:
self.label1.alpha = 1.0
let delay = 2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
// After 2 seconds this line will be executed
self.label1.alpha = 0.0
}
'2' is the seconds you want to wait
Regards
How do I delay running a line of code until animations are finished? (DispatchGroup & DispatchQueue)
Simplist Option
Okay, so there's a lot of stuff here, for one, you can remove the animation group, as if its only purpose is to help run code when the animations are finished, then we won't need it.
Secondly, animations come with a completion
callback. So change your Fade away coin image
to this:
UIView.animate(withDuration: 5, delay: 6, options: []) {
self.coinImage.alpha = 0.5
} completion: { _ in
self.coinImage.layer.removeAllAnimations()
}
This means that after the 6 second delay and the 5 second animation, the coins layer animations will be removed
Another Option
If this doesn't create the desired effect, then instead you can try this (I personally try to avoid using this where I can as it can be prone to breaking if animation times are changed):
DispatchQueue.main.asyncAfter(deadline: .now() + <#Delay in seconds#>) {
<#code#>
}
This will run the code inside the closure after the given number of seconds.
How to do arithmetic between int and float in Swift?
Depending on what you want your result to be, you should convert it to the appropriate type using that types init method.
eg.
var myInt = 5;
var myDouble = 3.4;
If I want a double for example in my result
var doubleResult = Double(myInt) + myDouble;
if I want an integer instead, please note the double will be truncated.
var intResult = myInt + Int(myDouble)
The problem I see in your example is you're trying to do an add operation and then convert it but both values needs to be the same before you perform the addition.
Apple has made it quiet strict to avoid type mis-match and conversion errors. Sometimes this can be a bit 'too strict' for dev coming from other languages, I was annoyed at first but I got used to it.
Related Topics
Uitextview Change Text Color of Specific Text
How to Handle Two Different Types in an Array in Swift for a Uitableview
Why Does the Following Code Crash on an iPhone 5 But Not an iPhone 5S
Core Data Predicate Not Working
How to Access Firebase Variable Outside Firebase Function
Most Efficient Way to Access Multi-Dimensional Arrays in Swift
Toggle Selection in a List - Swiftui
Xcode & Swift - Window Without Title Bar But with Close, Minimize and Resize Buttons
Xcode Playgrounds Can't Access Swift Files in Sources Folder
How to Compare Just the Time of a Date in Swift
Fatal Error: Array Index Out of Range in Swift Xcode6
Disable Scrolling in Swiftui List/Form
Play Local Audio File with Avaudioplayer
Physicsbody: Could Not Create Physics Body
Executing Text-To-Speech in Order
Swift Struct Initialization, Making Another Struct Like String
Uibarbuttonitem Doesn't Work When Created as a Property, But Does When Created in a Function