Reputation: 101
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
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
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