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

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.

Related

Notification center values is not getting update for first, second time

I have an pagMenuController on did select method I am passing the index. And in another vc I am getting that index values and I needs to show the view respective with incoming index value.
Code in my FirstVC:
func pageMenuController(_ pageMenuController: PageMenuController, didSelectMenuItem index: Int, direction: PageMenuNavigationDirection) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateView"), object: nil, userInfo: ["indexValue": index])
}
Code in my SecondVC:
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(ContViewController.incomingNotification(_:)), name: NSNotification.Name(rawValue: "updateView"), object: nil)
}
#objc func incomingNotification(_ notification: Notification) {
if let indexVal = notification.userInfo?["indexValue"] as? Int {
print(indexVal)
}
}
When ever my screen appears, I needs to get the index values. But when I click on my menu items first, second time index values in not showing. 3rd, and above time its coming. what I have missed.
Any solutions?
Thank you
move your observer to viewdidload
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ContViewController.incomingNotification(_:)), name: NSNotification.Name(rawValue: "updateView"), object: nil)
}

NotificationCenter addObserver() issue

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

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

Resources