How to create a delay in Swift?
Instead of a sleep, which will lock up your program if called from the UI thread, consider using NSTimer
or a dispatch timer.
But, if you really need a delay in the current thread:
do {
sleep(4)
}
This uses the sleep
function from UNIX.
How to program a delay in Swift 3
After a lot of research, I finally figured this one out.
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
// Code you want to be delayed
}
This creates the desired "wait" effect in Swift 3 and Swift 4.
Inspired by a part of this answer.
Delaying function in swift
You can use GCD (in the example with a 10 second delay):
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 and Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
Swift 5 or Later
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
How to create multiple delays using a dispatch queue?
// Code I want to run every 1 second for 20 times
What you're looking for is a Timer.
https://developer.apple.com/documentation/foundation/timer
var timer : Timer?
var times = 0
@objc func fired(_ t:Timer) {
times += 1
print("do your code") // do your code here
if times == 20 {
t.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self,
selector: #selector(fired), userInfo: nil,
repeats: true)
}
You will see that print("do your code")
runs every 1 second 20 times.
Is there a way to delay a return-Statement in Swift?
You are looking for a closure, a.k.a. completion handler.
return
executes immediately and there is no way to delay that. Instead, you can use completion handlers, which work by passing in a closure as a parameter. This closure can then be called after a delay.
/// closure here!
func returnLate(completion: @escaping ((String) -> Void)) {
var string = "Wrong"
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
string = "right"
completion(string) /// similar to `return string`
}
}
override func viewDidLoad() {
super.viewDidLoad()
returnLate { string in
print("String is \(string)") /// String is right
}
}
How can I put a time delay within an IF statement in Swift?
Taking aheze's code suggestion and adding it to my program in the proper position has worked, and now the app pauses for a second upon successful login. This doesn't work entirely as I need it to, as the successful login message simply does not appear now, probably due to the time delay, however I'm sure I can work around this as it appears to be simple issue!
aheze's code inserted into my program:
if self.username == storedUsername && self.password == storedPassword {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.authenticationDidSucceed = true
}
Once again, thanks for the help, and I hope I've done it right!
How to add a delay to a sound being played with swift
I make a new project and change your code to this:
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var magicBall: UIImageView!
// you never used this
//var magicBallDisplay = 1
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
magicBall.image = #imageLiteral(resourceName: "theanswerisyes")
}
@IBAction func askButtonPressed(_ sender: UIButton) {
// because you have audio file and image with equal name i made array of string
let magicBallArray = [ "yes","no","theanswerisyes","noidea","askagainlater"]
// check if i get not null item
guard let choosedImageName = magicBallArray.randomElement() else {return}
print(choosedImageName)
// set image with random picked name
magicBall.image = UIImage(named: choosedImageName)
// play ask sound
playSound(fileName: "Ask", fileType: "wav")
// play picked image sound after 10 second from now()
// change number to your needed time
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.playSound(fileName: choosedImageName, fileType: "mp3")
})
}
private func playSound(fileName: String, fileType: String)
{
// check if you find the audio file
guard let url = Bundle.main.path(forResource: fileName, ofType: fileType) else {
print("path not found")
return
}
// make NSURL from path
let soundURL = NSURL(fileURLWithPath: url)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
}
I explain code for you.
I didn't enable the button. you can improve this code when you came stronger in swift
30 Minute Post Delay Not Working With Swift
Instead of storing whether or not the user is allowed to post, store their last post time and compare it to the current time.
Related Topics
Ios: What's the Fastest, Most Performant Way to Make a Screenshot Programmatically
Why Do We Use Use_Frameworks! in Cocoapods
Nspersistentcontainer Concurrency for Saving to Core Data
iOS App Error - Can't Add Self as Subview
Disable Uipageviewcontroller Bounce
Restrict to Certain iOS Target Devices for App Store Submission
Loading a Reusable Uitableviewcell from a Nib
App "Does Not Contain the Correct Beta Entitlement"
Dyld: Symbol Not Found: _Nsurlauthenticationmethodclientcertificate When Trying to Run iOS App
How to Initialize/Instantiate a Custom Uiview Class with a Xib File in Swift
Alternative to Dtsendsignalflag to Identify Key Events in Instruments
Get Size of a View in React Native
Loading an Image into Uiimage Asynchronously
Scrollview Gesture Recognizer Eating All Touch Events
How to Find File Uti for File, Withouth Pathextension, in a Path in Swift
How to Resize Uiimageview Based on Uiimage's Size/Ratio in Swift 3