Notification Center not working. The observer is not being called - ios

I am trying to call a function from another class in Swift and NotificationCenter is an option to do that so I started with the addObserver.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(toggleSideMenu), name: NSNotification.Name("callToggleSideMenu"), object: nil)
}
#objc func toggleSideMenu(){
if isMenuOpen {
sideContainer.constant = -260
} else {
sideContainer.constant = 0
}
}
And in the other class I have added the (post):
#objc func clickOnButton(button: UIButton) {
NotificationCenter.default.post(name: NSNotification.Name("callToggleSideMenu"), object: nil)
}
Everything seems ok but I do not know why it is not working. I have seen a lot of the same issue here in stackoverflow but no answer solved my issue.

Function definition is not correct. It should be :
#objc func toggleSideMenu(_ notification: Notification){
if isMenuOpen {
sideContainer.constant = -260
} else {
sideContainer.constant = 0
}
}
Call it using :
NotificationCenter.default.addObserver(self, selector: #selector(toggleSideMenu(_:)), name: NSNotification.Name("callToggleSideMenu"), object: nil)

Related

Using #objc in Swift 5 protocols

I have an issue with using #objc code in swift protocols and was wondering if there is a workaround for that.
Currently, I have code:
import UIKit
#objc
protocol TrackScreenshot {
func registerObserver()
func removeObservers()
}
extension TrackScreenshot where Self: ScreenTracking {
func registerObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(trackScreenshot), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
}
func removeObservers() {
NotificationCenter.default.removeObserver(self, name: UIApplication.userDidTakeScreenshotNotification, object: nil )
}
func trackScreenshot() {
print(screenName.rawValue)
}
}
So I want to inherit the TrackScreenshot protocol and make screens easily trackable.
BUT there is an issue.
registerObserver() method on #selecor asks to add #objc to trackScreenshot method, but if I do so, Xcode complains on trackScreenshot() line and telling: #objc can only be used with members of classes, #objc protocols, and concrete extensions of classes
Is there a way to fix this?
Also tried:
NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: nil) { _ in
print(self.screenName.rawValue)
}
but it's not working, and the observer can't be removed and remains in the circle, so prints all the previous screen names when a new screen is opened.
Any help is more then welcome! Thanks in advance!
I would use the closure form of notification observation rather than a selector/method:
protocol TrackScreenshot {
func registerObserver(handler: (()->Void)?)
func removeObservers()
}
extension TrackScreenshot where Self: ScreenTracking {
func registerObserver(handler: (()->Void)?) {
NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: nil) { (notification) in
handler?()
}
}
func removeObservers() {
NotificationCenter.default.removeObserver(self, name: UIApplication.userDidTakeScreenshotNotification, object: nil )
}
}
Then your use is something like:
self.registerObserver { [weak self] in
guard let self = self else {
return
}
print("Screen shot")'
}
You can track screenshot notification using delegates too, feel free to refactor as per your need:
public protocol ScreenshotDelegate: AnyObject {
func screenshotDetected()
}
open class ScreenshotTracker: NSObject {
private weak var delegate: ScreenshotDelegate?
public init(delegate: ScreenshotDelegate) {
self.delegate = delegate
NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
delegate.screenshotDetected()
print("Screenshot notification")
}
}
}
ViewController Setup:
override func viewDidLoad() {
super.viewDidLoad()
let _ = ScreenshotTracker(delegate: self)
}
extension ViewController: ScreenshotDelegate {
func screenshotDetected() {
print("screenshot taken!!!")
}
}

NotificationCenter - text transfer between views

I have this code:
MainViewControler.swift:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(showAlertMessage(notification:)), name: Notification.Name("NotificationAlertMessage"), object: errorMessage.self)
}
#objc func showAlertMessage(notification: NSNotification) {
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \(notification.title)")
}
AlertStruct.swift:
struct errorMessage{
var title: String?
var description: String?
}
Propierties.swift
func showError(){
NotificationCenter.default.post(name: Notification.Name("NotificationAlertMessage"), object: errorMessage(title: "tytuł", description: "description"))
}
override func viewDidLoad() {
super.viewDidLoad()
showError()
}
Propierties.swift is child in containerView MainViewControler.
I would like to display the function ShowAlertMessage in my MainViewControler with data sent from Propierties -> func showError ()
How to do it? My code does not want to compile / work correctly :(
Your code is almost correct...Just update below method
#objc func showAlertMessage(notification: NSNotification) {
let object = notification.object as! errorMessage
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \(object.title)")
}
try this, tested
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(showAlertMessage(notification:)), name: Notification.Name("NotificationAlertMessage"), object: nil)
NotificationCenter.default.post(name: Notification.Name("NotificationAlertMessage"), object: nil, userInfo: ["object": ErrorMessage(title: "tytuł", description: "description")])
}
#objc func showAlertMessage(notification: NSNotification) {
if let errorMessage = notification.userInfo?["object"] as? ErrorMessage {
print("\(errorMessage.title), \(errorMessage.description)")
}
}

How to unregister an NSNotification in Swift iOS

I have two controllers
class CtrlA: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(CtrlB.self, selector: #selector(CtrlB.badge(notification:)), name: NSNotification.Name(rawValue: "badge"), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(CtrlB.self, name: NSNotification.Name(rawValue: "badge"), object: nil)
}
}
class CtrlB: UIViewController {
static func badge (notification: NSNotification) {
// blah blah
}
}
Whats the correct way to unregister the notification listener above?
I'm not certain this is correct:
NotificationCenter.default.removeObserver(CtrlB.self, name: NSNotification.Name(rawValue: "badge"), object: nil)
I don't think I can use self either, since it was registered on CtrlB.self
So the best way to implement the notification in your project is create one class called NotificationManager inside that declare one dictionary in which you can always update the observers
class NotificationManager {
var observers = [String: AnyObject]()
}
Create addObserver method, post notification method and remove
observer method inside the same class.
func postNotification(_ name: String, userInfo: [AnyHashable: Any]? = nil) {
NotificationCenter.default.post(name: name, object: nil, userInfo: userInfo)
}
func addObserver(_ name: String, block: #escaping (Notification) -> Void) {
//if observer is already in place for this name, remove it
removeObserverForName(name)
let observer = NotificationCenter.default.addObserver(forName: name), object: nil, queue: OperationQueue.main, using: block)
self.observers[name] = observer
}
func removeObserver(_ name: name) {
guard let observer = self.observers[name] else { return }
NotificationCenter.default.removeObserver(observer)
self.observers.removeValue(forKey: name)
}
//Removes all observers
func removeAllObservers() {
for observer in self.observers.values {
NotificationCenter.default.removeObserver(observer)
}self.observers = [:]
}
So access the above method in any of your class wherever its required and it will take care of everything. This will also prevent crash in your code. If try to remove the same observer more than one time.
I am not sure why you are registering/unregistering to notifications with a class and not an instance. 'CtrlB.self' - will not give you an instance of the CtrlB class, in fact it will return a class itself.
Instead you should use something like this:
class CtrlA {
let ctrlBInstance = CtrlB()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(ctrlBInstance, selector: #selector(CtrlB.badge(notification:)), name: NSNotification.Name(rawValue: "badge"), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(ctrlBInstance, name: NSNotification.Name(rawValue: "badge"), object: nil)
}
}
And your ClassB should look like this in this case:
class CtrlB {
func badge (notification: NSNotification) {
// blah blah
}
}
You need to get the instance of the observer,which you haven't declared...
for instance you need to set class variable secondA...
class CtrlA: UIViewController {
var secondController: CtrlB?
override func viewDidLoad()
{
super.viewDidLoad()
if let unwrappedController = storyboard.instantiateViewController(withIdentifier: "someViewController") as? CtrlB
{
secondController = unwrappedController
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let secondController = secondController
{
NotificationCenter.default.addObserver(CtrlB.self, selector: #selector(CtrlB.badge(notification:)), name: NSNotification.Name(rawValue: "badge"), object: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let secondController = secondController
{
NotificationCenter.default.removeObserver(CtrlB.self, name: NSNotification.Name(rawValue: "badge"), object: nil)
}
}
//Also don't forget to remove listening on deinit
deinit
{
if let secondController = secondController
{
NotificationCenter.default.removeObserver(secondController, name: NSNotification.Name(rawValue: "badge"), object: nil)
}
}
}
class CtrlB: UIViewController {
//Here you go with notification...
static func badge (notification: NSNotification) {
// blah blah
}
}

NSNotfication.addObserver - Update to current Swift Syntax?

Currently following a tutorial, however, some of the syntax is outdated. Basically the code should show and hide the user keyboard. I get some syntax errors with the addObserver method and Swift wants me to use key path instead, however, if i use the auto 'fix-it' i get even more errors. Can anyone help me out with this? Thanks!
NSNotification.addObserver(self, selector: #selector(keyboardwillShow), name: .UIKeyboardWillShow, nil)
NSNotification.addObserver(self, selector: #selector(keyboardwillHide), name: .UIKeyboardWillHide, nil)
func keyboardwillShow(_notification:NSNotification) {
keyboard = (_notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
UIView.animate(withDuration: 0.4) {
self.scrolledView.frame.size.height = self.scrollViewHeight - self.keyboard.height
}
}
func keyboardwillHide(_notification:NSNotification) {
UIView.animate(withDuration: 0.5) {
self.scrolledView.frame.size.height = self.view.frame.height
}
}
I get the debug message: "Incorrect argument labels in call(have _selector:name, expected _forKeyPath:options:context"
Your function has argument, That is missing when you add it in observer
And you have to use NotificationCenter.default.addObserver not NotificationCenter.addObserver
let selectorForKeyBoardWillShow: Selector = #selector(ViewController.keyboardWillShow(_:))
let selectorForKeyBoardWillHide: Selector = #selector(ViewController.keyboardWillHide(_:))
// MARK: - Functions
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillShow, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillHide, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// MARK: Keyboard Observer
func keyboardWillShow(_ notification: Notification) {
}
func keyboardWillHide(_ notification: Notification) {
}

In an extension, how to identify device orientation on iOS 10. It is not properly responding, or I am doing it wrong?

I've tried multiple methods to add an observer, and call this function:
In viewDidLoad
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
and also;
deinit {
NotificationCenter.default.removeObserver(self)
}
func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
// all return false
print(UIDevice.current.orientation.isFlat)
print(UIDevice.current.orientation.isPortrait)
print(UIDevice.current.orientation.isLandscape)
print(UIDevice.current.orientation.isValidInterfaceOrientation)
}
I've also tried:
UIDevice.current.orientation.isLandscape
and all the other possibilities like .isLandscape, .IsFlat, etc and none of them seem to be working either.
You forgot to call beginGeneratingDeviceOrientationNotifications(). So the device will never send UIDeviceOrientationDidChange. And that is also why UIDevice.current.orientation doesn't work; it only works if you have called beginGeneratingDeviceOrientationNotifications(). The docs are quite clear about this.
Example:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(
self, selector: #selector(deviceOrientationDidChange),
name: .UIDeviceOrientationDidChange, object: nil)
}
func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
}
}
Output:
0
1
3
2
4
1
This is how I ended up getting the information:
func deviceOrientation() {
if UIScreen.main.bounds.size.width < UIScreen.main.bounds.size.height {
print("portrait")
} else {
print("landscape")
}
}

Resources