will3321
will3321

Reputation: 101

Wait until NSNotification is Received

I would like to have a method that pauses execution until a notification is received before continuing. It will then continue execution after the notifications received. What is the best way to go about doing this?

Upvotes: 2

Views: 1941

Answers (2)

Bart van Kuik
Bart van Kuik

Reputation: 4862

Waiting for a notification, with a timeout, in Swift 5

    var accountUpdateNotification: Notification?
    NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: ACCOUNT_UPDATE_NOTIFICATION),
                                           object: nil, queue: nil) { notification in
        accountUpdateNotification = notification
    }
    
    // Do action that posts notification

    let startTime = Date()
    let endTime = startTime.addingTimeInterval(10)
    while accountUpdateNotification == nil {
        let nextTime = Date().addingTimeInterval(0.1)
        RunLoop.current.run(until: nextTime)
        if nextTime > endTime {
            NSLog("Didn't receive notification in time")
            return
        }
    }

Upvotes: 0

A Trâu
A Trâu

Reputation: 305

you can using NSRunLoop

- (BOOL)method {
__block BOOL finish = NO;
[[NSNotificationCenter defaultCenter] addObserverForName:@"myNotification" object:nil queue:nil usingBlock:^(NSNotification *note) {
    finish = YES;
}];

while(!finish) {
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}

return YES;
}

Upvotes: 5

Related Questions