wyślij po-GCD w Swift?

Przejrzałem iBook od Apple i nie mogłem znaleźć jego definicji:

Czy ktoś może wyjaśnić strukturę dispatch_after?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)

25 answers

Jaśniejsze pojęcie struktury:

dispatch_after(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t?)

dispatch_time_t jest UInt64. dispatch_queue_t jest w rzeczywistości typu aliased do NSObject, ale powinieneś po prostu użyć swoich znanych metod GCD, aby uzyskać kolejki. Blok to szybkie zamknięcie. W szczególności dispatch_block_t definiuje się jako () -> Void, co jest równoważne () -> ().

Przykładowe użycie:

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    print("test")
}

EDIT:

Polecam użycie @matt ' s really nice delay function.

Edytuj 2:

W Swift 3, będą nowe opakowania do GCD. Zobacz też: https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

Oryginalny przykład byłby napisany w następujący sposób w języku Swift 3:

let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    print("test")
}

Zauważ, że możesz zapisać deadlineTime jako DispatchTime.now() + 1.0 i uzyskać ten sam wynik, ponieważ operator + jest nadpisany w następujący sposób (podobnie dla -):

  • func +(time: DispatchTime, seconds: Double) -> DispatchTime
  • func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime

Oznacza to, że jeśli nie użyj DispatchTimeInterval enum i po prostu napisz numer, zakłada się, że używasz sekund.

 754
Author: Cezary Wojcik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:09

Używam dispatch_after tak często, że napisałem funkcję najwyższego poziomu, aby uprościć składnię:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

A teraz możesz mówić Tak:

delay(0.4) {
    // do stuff
}

Wow, język, w którym można poprawić język. Co może być lepsze?


Aktualizacja dla Swift 3, Xcode 8 Seed 6

Wydaje się, że prawie nie warto się martwić, teraz, gdy poprawili składnię wywołania:

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
 1102
Author: matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-31 19:32:46

Swift 3+

To jest super-łatwe i eleganckie w Swift 3+:

DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
    // ...
}

Starsza Odpowiedź:

Aby rozwinąć odpowiedź Cezarego, która zostanie wykonana po 1 nanosekundzie, musiałem wykonać następujące czynności, aby wykonać po 4 i pół sekundy.

let delay = 4.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), block)

Edit: odkryłem, że mój oryginalny kod był nieco zły. Niejawne wpisanie powoduje błąd kompilacji, jeśli nie rzucisz Nsec_per_sec Na Double.

Gdyby ktoś mógł zaproponować bardziej optymalne rozwiązanie, byłbym chętnie posłucham.

 134
Author: brindy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-13 14:54:33

Składnia Matta jest bardzo ładna i jeśli chcesz unieważnić blok, możesz użyć tego:

typealias dispatch_cancelable_closure = (cancel : Bool) -> Void

func delay(time:NSTimeInterval, closure:()->Void) ->  dispatch_cancelable_closure? {

    func dispatch_later(clsr:()->Void) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(time * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), clsr)
    }

    var closure:dispatch_block_t? = closure
    var cancelableClosure:dispatch_cancelable_closure?

    let delayedClosure:dispatch_cancelable_closure = { cancel in
        if closure != nil {
            if (cancel == false) {
                dispatch_async(dispatch_get_main_queue(), closure!);
            }
        }
        closure = nil
        cancelableClosure = nil
    }

    cancelableClosure = delayedClosure

    dispatch_later {
        if let delayedClosure = cancelableClosure {
            delayedClosure(cancel: false)
        }
    }

    return cancelableClosure;
}

func cancel_delay(closure:dispatch_cancelable_closure?) {

    if closure != nil {
        closure!(cancel: true)
    }
}

Użyj zgodnie z instrukcją

let retVal = delay(2.0) {
    println("Later")
}
delay(1.0) {
    cancel_delay(retVal)
}

Kredyty

Link powyżej wydaje się być w dół. oryginalny kod obiektu z Github

 83
Author: Waam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:43

Najprostsze rozwiązanie w Swift 3.0 & Swift 4.0 & Swift 5.0

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Użycie

delayWithSeconds(1) {
   //Do something
}
 30
Author: Vakas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-22 07:03:57

Apple ma dispatch_after snippet dla Objective-C :

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    <#code to be executed after a specified delay#>
});

Oto ten sam fragment przeniesiony do Swift 3:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + <#delayInSeconds#>) {
  <#code to be executed after a specified delay#>
}
 22
Author: Senseful,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-04 13:51:56

Innym sposobem jest wydłużenie Podwójnego w ten sposób:

extension Double {
   var dispatchTime: dispatch_time_t {
       get {
           return dispatch_time(DISPATCH_TIME_NOW,Int64(self * Double(NSEC_PER_SEC)))
       }
   }
}

Wtedy możesz użyć go tak:

dispatch_after(Double(2.0).dispatchTime, dispatch_get_main_queue(), { () -> Void in
            self.dismissViewControllerAnimated(true, completion: nil)
    })

Podoba mi się funkcja opóźnienia Matta, ale po prostu z preferencji wolałbym ograniczyć przekazywanie zamknięć.

 14
Author: garafajon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-11 05:23:29

W Swift 3.0

Kolejki wysyłkowe

  DispatchQueue(label: "test").async {
        //long running Background Task
        for obj in 0...1000 {
            print("async \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.async(execute: { 
            print("UI update on main queue")
        })

    }

    DispatchQueue(label: "m").sync {
        //long running Background Task
        for obj in 0...1000 {
            print("sync \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.sync(execute: {
            print("UI update on main queue")
        })
    }

Wysyłka po 5 sekundach

    DispatchQueue.main.after(when: DispatchTime.now() + 5) {
        print("Dispatch after 5 sec")
    }
 8
Author: Mohammad Sadiq Shaikh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-14 05:33:05

Wersja Swift 3.0

Po zamknięciu funkcji wykonaj jakieś zadanie po opóźnieniu w głównym wątku.

func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
       onCompletion()
    })
}

Wywołaj tę funkcję w następujący sposób:

performAfterDelay(delay: 4.0) {
  print("test")
}
 4
Author: Himanshu Mahajan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-03 10:50:54

1) Dodaj tę metodę jako część rozszerzenia UIViewController.

extension UIViewController{
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue(), block)
    }
}

Wywołanie tej metody NA VC:

    self.runAfterDelay(5.0, block: {
     //Add code to this block
        print("run After Delay Success")
    })

2)

performSelector("yourMethod Name", withObject: nil, afterDelay: 1)

3)

override func viewWillAppear(animated: Bool) {

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue(), { () -> () in
    //Code Here
})

/ / Forma Zwarta

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue()) {
    //Code here
 }
}
 4
Author: A.G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-16 05:28:30

Chociaż nie było to pierwotne pytanie OP, niektóre pytania związane z tym pytaniem zostały oznaczone jako duplikaty tego pytania, więc warto w tym miejscu umieścić odpowiedź NSTimer.

NSTimer vs dispatch_after

  • NSTimer jest bardziej wysoki, podczas gdy dispatch_after jest bardziej niski.
  • NSTimer jest łatwiejsze do anulowania. Anulowanie dispatch_after wymaga napisania więcej kodu.

Opóźnianie zadania za pomocą NSTimer

Utwórz instancję NSTimer.

var timer = NSTimer()

Start zegar z opóźnieniem, którego potrzebujesz.

// invalidate the timer if there is any chance that it could have been called before
timer.invalidate()
// delay of 2 seconds
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 

Dodaj funkcję, która zostanie wywołana po opóźnieniu (używając dowolnej nazwy użytej do parametru selector powyżej).

func delayedAction() {
    print("Delayed action has now started."
}

Uwagi

  • jeśli chcesz anulować akcję przed jej wykonaniem, po prostu zadzwoń timer.invalidate().
  • do wielokrotnego użycia repeats: true.
  • Jeśli masz zdarzenie jednorazowe bez konieczności anulowania, nie ma potrzeby tworzenia zmiennej instancji timer. Następujący Testament wystarczy:

    NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 
    
  • Zobacz moją pełniejszą odpowiedź tutaj .

 3
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:09

Dla wielu funkcji Użyj tego. Jest to bardzo pomocne w użyciu animacji lub Activity loader dla funkcji statycznych lub dowolnej aktualizacji interfejsu użytkownika.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
            // Call your function 1
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                // Call your function 2
            }
        }

Na przykład-użyj animacji przed przeładowaniem widoku tableView. Lub innej aktualizacji interfejsu użytkownika po animacji.

*// Start your amination* 
self.startAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
                *// The animation will execute depending on the delay time*
                self.stopAnimation()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    *// Now update your view*
                     self.fetchData()
                     self.updateUI()
                }
            }
 3
Author: Rahul Singha Roy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-11 09:56:04

W Swift 5, użyj poniżej:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }
 3
Author: Zgpeace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-09 01:20:05

To mi pomogło.

Swift 3:

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

Objective-C:

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});
 2
Author: garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-26 02:24:32

Swift 3 & 4:

Możesz utworzyć rozszerzenie na DispatchQueue i dodać funkcję delay, która wewnętrznie używa funkcji Asyncafter DispatchQueue

extension DispatchQueue {
    static func delay(_ delay: DispatchTimeInterval, closure: @escaping () -> ()) {
        let timeInterval = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: timeInterval, execute: closure)
    }
}

Użycie:

DispatchQueue.delay(.seconds(1)) {
    print("This is after delay")
}
 2
Author: Suhit Patil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 10:17:40

Kolejny helper opóźniający kod, który jest W 100% szybki w użyciu i opcjonalnie pozwala wybrać inny wątek , aby uruchomić opóźniony kod z:

public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
    let dispatchTime = DispatchTime.now() + seconds
    dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}

public enum DispatchLevel {
    case main, userInteractive, userInitiated, utility, background
    var dispatchQueue: DispatchQueue {
        switch self {
        case .main:                 return DispatchQueue.main
        case .userInteractive:      return DispatchQueue.global(qos: .userInteractive)
        case .userInitiated:        return DispatchQueue.global(qos: .userInitiated)
        case .utility:              return DispatchQueue.global(qos: .utility)
        case .background:           return DispatchQueue.global(qos: .background)
        }
    }
}

Teraz po prostu opóźnij kod w głównym wątku tak:

delay(bySeconds: 1.5) { 
    // delayed code
}

Jeśli chcesz opóźnić kod do innego wątku :

delay(bySeconds: 1.5, dispatchLevel: .background) { 
    // delayed code that will run on background thread
}

Jeśli wolisz Framework , który ma również kilka bardziej przydatnych funkcji, to checkout HandySwift. Ty możesz dodać go do swojego projektu poprzez Kartaginę, a następnie użyć go dokładnie tak, jak w powyższych przykładach, np.:

import HandySwift    

delay(bySeconds: 1.5) { 
    // delayed code
}
 1
Author: Jeehut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-21 04:43:18

Zawsze wolę używać rozszerzenia zamiast darmowych funkcji.

Swift 4

public extension DispatchQueue {

  private class func delay(delay: TimeInterval, closure: @escaping () -> Void) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
  }

  class func performAction(after seconds: TimeInterval, callBack: @escaping (() -> Void) ) {
    DispatchQueue.delay(delay: seconds) {
      callBack()
    }
  }

}

Użyj w następujący sposób.

DispatchQueue.performAction(after: 0.3) {
  // Code Here
}
 1
Author: Hardeep Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-21 06:31:32

Opóźnianie wywołania GCD za pomocą asyncAfter w swift

let delayQueue = DispatchQueue(label: "com.theappmaker.in", qos: .userInitiated)
let additionalTime: DispatchTimeInterval = .seconds(2)

Możemy opóźnić jak * * mikrosekundy,milisekundy,nanosekundy

delayQueue.asyncAfter(deadline: .now() + 0.60) {
    print(Date())
}

delayQueue.asyncAfter(deadline: .now() + additionalTime) {
    print(Date())
}
 1
Author: Sanjay Mali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-13 10:01:43

In Swift 4

Użyj tego fragmentu:

    let delayInSec = 1.0
    DispatchQueue.main.asyncAfter(deadline: .now() + delayInSec) {
       // code here
       print("It works")
    }
 1
Author: BlackRock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-10 14:29:52
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // ...
});

Funkcja dispatch_after(_:_:_:) przyjmuje trzy parametry:

Opóźnienie
Kolejka wysyłkowa
blok lub zamknięcie

Funkcja dispatch_after(_:_:_:) wywołuje blok lub zamknięcie w kolejce wysyłania, które jest przekazywane do funkcji po określonym opóźnieniu. Zauważ, że opóźnienie jest tworzone za pomocą funkcji dispatch_time(_:_:). Pamiętaj o tym, ponieważ używamy tej funkcji również w języku Swift.

Polecam przejść przez tutorial raywenderlich Dispatch tutorial

 1
Author: CrazyPro007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-25 13:38:07

Użyj tego kodu, aby wykonać pewne zadania związane z interfejsem po 2,0 sekundach.

            let delay = 2.0
            let delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
            let mainQueue = dispatch_get_main_queue()

            dispatch_after(delayInNanoSeconds, mainQueue, {

                print("Some UI related task after delay")
            })

Wersja Swift 3.0

Po zamknięciu funkcji wykonaj jakieś zadanie po opóźnieniu w głównym wątku.

func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
       onCompletion()
    })
}

Wywołaj tę funkcję w następujący sposób:

performAfterDelay(delay: 4.0) {
  print("test")
}
 0
Author: Himanshu Mahajan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-03 10:51:56

Teraz więcej niż syntaktyczny cukier dla asynchronicznych wysyłek w Grand Central Dispatch (GCD) w Swift.

Dodaj Podfile

pod 'AsyncSwift'

Wtedy możesz go użyć w ten sposób.

let seconds = 3.0
Async.main(after: seconds) {
print("Is called after 3 seconds")
}.background(after: 6.0) {
print("At least 3.0 seconds after previous block, and 6.0 after Async code is called")
}
 0
Author: Tim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-03 07:12:04

Swift 4 ma dość krótki sposób na to:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
    // Your stuff here
    print("hello")
}
 0
Author: Vlady Veselinov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-17 01:48:39

Oto synchroniczna wersja asyncAfter w języku Swift:

let deadline = DispatchTime.now() + .seconds(3)
let semaphore = DispatchSemaphore.init(value: 0)
DispatchQueue.global().asyncAfter(deadline: deadline) {
    dispatchPrecondition(condition: .onQueue(DispatchQueue.global()))
    semaphore.signal()
}

semaphore.wait()

Wraz z asynchronicznym:

let deadline = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadline) {
    dispatchPrecondition(condition: .onQueue(DispatchQueue.global()))
}
 0
Author: Maxim Makhun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-29 20:56:06

Aby wykonać funcję lub kod po opóźnieniu użyj następnej metody

DispatchQueue.main.asyncAfter(deadline: .now() + 'secondsOfDelay') {
        your code here...
    }

Przykład - w tym przykładzie funcja getShowMovies zostanie wykonana po 1 sekundzie

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        self.getShowMovies()
    }
 -1
Author: Iker Solozabal Granados,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-09 12:42:02