-(void)viewDidAppear:(BOOL)animated {
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {
NSLog(@"SShot");
}];
}
- (void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
NSLog(@"VWD");
}
-(void)viewDidDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
NSLog(@"VDD");
}
I am getting SShot
logged in console even after I have removed the observer.
Is there any other way to remove UIApplicationUserDidTakeScreenshotNotification
observer.
Harris code is correct except a small detail that for Swift 4 it is now
private var observer: Any! and not private var observer: NSObjectProtocol! So code should be:
private var observer: Any!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
//do something
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(observer)
}
Here is how to do it in Swift 4...
private var observer: Any!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
//do something
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(observer)
}
From Apple Doc:
To unregister observations, you pass the object returned by this method to removeObserver:. You must invoke removeObserver: or removeObserver:name:object: before any object specified by addObserverForName:object:queue:usingBlock: is deallocated.
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];
You're trying to remove the worng observer, self
is not the observer here, the observer is the object returned by the add method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With