NotificationCenter addObserver() issue - ios

I'm trying to enable segue into a specific view upon opening a local notification by using NotificationCenter.addObserver(...)
My code is
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(LocalNotificationViewController.test), name: ???, object: nil)
}
With test method to perform the segue to ViewController with identifier NotificationView which I'm not sure what to put...
#objc func SomeNotificationAct(notification: NSNotification){
DispatchQueue.main.async() {
self.performSegue(withIdentifier: "NotificationView", sender: self)
}
}
My main question is how do I know the name of my local notification to put into the NotificationCenter.addObserver(...) method?

You will need to create extension for Notification name like,
extension Notification.Name {
static let hello1 = Notification.Name("HelloNotifcationName")
static let hello2 = Notification.Name("HelloNotifcationName2")
}
and use it like this,
NotificationCenter.default.addObserver(self, selector: #selector(setToHelloName1(notification:)), name: .hello1, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(setToHelloName2(notfication:)), name: .hello2, object: nil)
You can find further reference or tutorial,here

Related

Modal UIViewController can't receive NSNotifications

I have a modal UIViewController:
let rVC = RecoveryViewController()
rVC.modalPresentationStyle = .overFullScreen
self.present(rVC, animated: true, completion: nil)
In viewDownload of this ViewController I have a function user.checkUserData() that would send NSNotifications when the job is done.
And, of course, observers for any of these notifications:
NotificationCenter.default.addObserver(self, selector: #selector(RecoveryViewController.userVIP), name: userDataIsHere, object: nil)
But it seems that my modal ViewController is not able to receive any notifications, because nothing is happening. At the same time if I tried to add such observer to the parent UIViewController (non-modal), it'd work like a charm (actually, I checked).
My notifications are quite simple, and
let userDataIsHere = Notification.Name("userDataIsHere")
NotificationCenter.default.post(name: userDataIsHere, object: nil)
What am I doing wrong here?
Try this.
class ViewController: UIViewController {
let userDataIsHere = Notification.Name("userDataIsHere")
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(modalPopUp), name: userDataIsHere, object: nil)
}
#objc func modalPopUp() {
let rVC = RecoveryViewController()
rVC.modalPresentationStyle = .overFullScreen
self.present(rVC, animated: true, completion: nil)
}
}
Make sure you completed below things:
1) Notification Registered before use
2) Notification identifier must be same.
Here is my code for notification:
1) Registered Notification in viewDidLoad:
let notificationName = Notification.Name("NotificationIdentifier")
NotificationCenter.default.addObserver(self, selector: #selector(yourFunctionName), name: notificationName, object: nil)
#objc func yourFunctionName(notification: NSNotification){
//do stuff
print("Called..")
}
2) Post notification when you required:
// Post notification
let notificationName = Notification.Name("NotificationIdentifier")
NotificationCenter.default.post(name: notificationName, object: nil)

Change UIScrollView Offset to top from another viewController in Swift 4

I have mainViewController and inside have scrollView and I have secondViewController I want to change scrollView offset to top from secondViewController when I want to try it with NSNotificationCenter gives me ;
: unrecognized selector sent to instance 0x7ff83e024200'
How can I fix it ?
My codes under below.
mainViewController
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: "gotop:", name: NSNotification.Name(rawValue: "gotop"), object: nil)
}
func gotop(){
scrollView.setContentOffset(CGPoint(x:0, y:0), animated: false)
}
secondViewController
#IBAction func goButton (sender : UIButton){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "gotop"), object: nil)
}
check your addObserver code, selector should have below signature
NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.goTop(notification:)), name: Notification.Name("gotop"), object: nil)
Method handler for received Notification:
func goTop(notification: Notification){
scrollView.setContentOffset(CGPoint(x:0, y:0), animated: false)
}
For posting notification
NotificationCenter.default.post(name: Notification.Name("gotop"), object: nil)
Remove Notification in denit
deinit {
NotificationCenter.default.removeObserver((self, name: Notification.Name("gotop"), object: nil)
}
I have used below code in my project to add notification :
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.gotop), name: NSNotification.Name(rawValue: "gotop"), object: nil)
Try if it works in your scenario.
the definition of your "goTop" func is wrong :
instead of
func gotop(){
//do your stuff
}
try this :
func gotop(notification : NSNotification){
//do your stuff
}
let me know if this solve your problem.

NotificationCenter is not calling the selector

I've searched about this but the problem still exist for me. I found this great question but unfortunately it didn't work for me. This is the first time I'm working with NotificationCenter and the need to use this first occurs when I wanted to pass data to a viewcontroller under a tab of XLPagerTabStrip.
So here is how I am posting the Notification:
if let doc_ID = mainDoctorsArray[sender.tag].doctors_id {
NotificationCenter.default.post(name: Notification.Name("docID"), object: nil, userInfo: ["value" : doc_ID])
}
In the class I've made for observing this notification I'm calling NotificationCenter.default.addObserver(self, selector: #selector(gotDocID), name: Notification.Name("docID"), object: nil)
The selector method is:
func gotDocID(notification:NSNotification) {
let userInfo:Dictionary<String,String> = notification.userInfo as! Dictionary<String,String>
if let item = userInfo["value"] {
getDoctorDetails(docID: Int(item)!)
//print(item,self)
}
}
I've also tried adding observer as:
NotificationCenter.default.addObserver(self, selector: #selector(AvailableViewController.gotDocID(notification:)), name: Notification.Name("docID"), object: nil) but still same result.
The issue is that func gotDocID(notification:NSNotification) is not being called.
UPDATE
Class which is posting the notification is ViewController.swift and the class which has the observer is AvailableViewController.swift
Based on a comment I've changed observer to NotificationCenter.default.addObserver(self, selector: #selector(AvailableViewController.gotDocID(notific‌​ation:)), name: Notification.Name("NotificationIdentifier"), object: nil) and this error is generated.
and also by doing the follow I'm getting the same error.
Value of type 'AvailableViewController' has no member 'gotDocID'
You can use the below code to post and get data.
//Post notification
NSNotificationCenter.defaultCenter().postNotificationName("docID", object: nil, userInfo: ["value" : doc_ID])
//Get data from observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AvailableViewController.gotDocID(_:)), name: "docID", object: nil)
//Method called after notification is posted.
func gotDocID(notification: NSNotification) {
if let image = notification.userInfo?["value"] as? String {
// do something with your data
}
}
Please check :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.gotDocID(notification:)), name: Notification.Name("docID"), object: nil)
}
#IBAction func saveButton(_ sender: UIButton) {
NotificationCenter.default.post(name: Notification.Name("docID"), object: nil, userInfo: ["value" : "123"])
}
#objc func gotDocID(notification:NSNotification) {
let userInfo:[String: String] = notification.userInfo as! [String: String]
if let item = userInfo["value"] {
print(item,self)
}
}
}
Add #objc to your function
#objc func gotDocID(notification:NSNotification) {
}
// Define identifier
let notificationName = Notification.Name("docID")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(AvailableViewController.gotDocID(notification:)), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil);
Why dont you try closure
Make sure your post notification occures.
Change
NotificationCenter.default.post(name: Notification.Name("docID") , object: ["value" : doc_ID])
NotificationCenter.default.addObserver(forName: Notification.Name("docID"), object: nil, queue: OperationQueue.main) { (notify) in
print(notify.object as! Dictionary<String,String>)
}

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) {
}

How to access UIViewController's varaibles inside "func applicationWillResignActive"? Swift, iOS xcode

I have my UIViewController class set up like this :
class ViewController: UIViewController {
var currentTask: NSURLSessionTask?
...
}
If the user presses Home button, I want to do
self.currentTask.cancel()
But how can I access this variable from AppDelegate.swift?
func applicationWillResignActive(application: UIApplication) {
}
in viewDidLoad() inside UIViewController class, add
// Add UIApplicationWillResignActiveNotification observer
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "resigningActive",
name: UIApplicationWillResignActiveNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "becomeActive",
name: UIApplicationDidBecomeActiveNotification,
object: nil
)
for Swift 4, iOS 11, use this:
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.resigningActive),
name: NSNotification.Name.UIApplicationWillResignActive,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.becomeActive),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
Finally add these two functions to your view controller:
#objc fileprivate func resigningActive() {
print("== resigningActive ==")
}
#objc fileprivate func becomeActive() {
print("== becomeActive ==")
}
For swift 4 and above you can use
UIApplication.willResignActiveNotification
and
UIApplication.didBecomeActiveNotification
for notification name.

Resources