Calling ViewController's Method from App Delegate - ios

Within my ViewController, Inbox, I'd like to call the method playAudio() from my App Delegate.
This is the method.
func playAudio(){
let nowPlaying = MPNowPlayingInfoCenter.defaultCenter()
let albumArtWork = MPMediaItemArtwork(image: UIImage(named: "testImage.jpg")!)
nowPlaying.nowPlayingInfo = [MPMediaItemPropertyTitle:"Sonnnngggg",
MPMediaItemPropertyArtist:"Arrrtttiiiissstttt",
MPMediaItemPropertyArtwork:albumArtWork]
audioPlayer.play()
}
And I'd like to call it from my App Delegate...
if event!.subtype == UIEventSubtype.RemoteControlPlay {
print("received remote play")
//audioPlayer.play()
Inbox.playAudio()
}
The one problem is that because I have a audioPlayer and everything within my Inbox ViewController, and that it's probably already playing audio, it doesn't make sense to make an instance of Inbox to call playAudio(). So, please let me know if there are any workarounds in Swift.
Thanks,
Liam

In AppDelegate change to:
if event!.subtype == UIEventSubtype.RemoteControlPlay {
print("received remote play")
//audioPlayer.play()
NSNotificationCenter.defaultCenter().postNotificationName("RemotePlayPressed", object: self)
}
Then in Inbox view controller's viewDidLoad add:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playAudio", name: "RemotePlayPressed", object: nil)
also add:
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
to Inbox view controller.

in your viewcontroller you reach your appdelegate via
(UIApplication.sharedApplication().delegate as! AppDelegate).playAudio()

You can instantiate the AppDelegate and call the function you want
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.someFunction()
But it not seems to be a good pratice...
NSNotificationCenter:
Use this code in the place you want to call the function:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "anotherFunction", name: "SomeNotification", object: nil)
change anotherFunction to the function name you want to call.
On AppDelegate:
NSNotificationCenter.defaultCenter().postNotificationName("SomeNotification", object: nil)

Related

Swift - observe static member change, without using property observer

I've got next situation: from the viewDidAppear I have to call the specific function ( to change the view controller to another one) when the special condition applied ( static member changes to True, another class access this static property and send True once the certain conditions apply)
If I do it like this with property observer:
//this is property of load view controller
static var isFilled: Bool = false {
didSet{
if isFilled == true {
print("data is Filled")
//load view controller - my present VC, which I want to switch
var loadVC = LoadViewController()
loadVC.changeViewController(vc: loadVC )
This is changeViewController function:
func changeViewController(vc: UIViewController) {
let sb = UIStoryboard(name: "Main", bundle: nil )
//main view controller - controller, which i want to Go to
var mainViewController = sb.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.present(mainViewController, animated: true, completion: nil)
}
It'll throw an error attempt to present viewcontroller whose view is not in the window hierarchy
And, it's performed inside LoadViewController class
As I understand, the only way to avoid this error is to call the function from the viewDidApper, which can't be used in this scenario, because i have to call it only when condition applied. Are there any alternatives to perform that w/o using property observer?
I'm sure there are multiple ways to perform this, and there are might be misconceptions from my side. I'm pretty fresh developer, and completely new to Swift. All the suggestions would be much appreciated.
You could use NotifiationCenter by registering a notification and then calling it whenever you want to update something, like "updateConversations" in a chat app. For example in viewDidLoad(), register your notification:
NotificationCenter.default.addObserver(self, selector: #selector(self.updateConversations(notification:)), name: NSNotification.Name(rawValue: "updateConversations"), object: nil)
Add this function into the class:
#objc func updateConversations(notification: NSNotification) {
if let id = notification.userInfo?["id"] as? Int,
let message = notification.userInfo?["message"] as? String {
// do stuff
}
}
Use the notification from anywhere in your app:
let info = ["id" : 1234, "message" : "I almost went outside today."]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateConversationsList"), object: self, userInfo: info)

How to removeObserver in Swift 5 using addObserver closure method

This is my first post.
I'm Japanese iOS engineer (just became this month).
I have a trouble with removeObserver method of NotificationCenter in Swift 5.
I added observer to ViewController (VC) by using closure type addObserver.
I want to remove this Observer when VC's deinitialization has called.
I wrote NotificationCenter.default.removeObserver(self) in VC's deinit method. But, this seemed not to work for me.
What's the problem???
Additionally, if my code has memory leak problem, let me know how to fix it.
Here's piece of my code.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] notification in
guard let self = self else { return }
self.loadWeather(notification.object)
}
}
deinit {
print(#function)
print("ViewController died")
NotificationCenter.default.removeObserver(self)
}
}
Closure-based addObserver
If you use the closure-based variant of addObserver, the token (not self) is
the observer. The notification center has no knowledge at all about
self in this situation. The documentation is not super clear on
this.
from Twitter
Meaning it's meaningless to do: NotificationCenter.default.removeObserver(self)
The docs recommend two ways:
Normal way
Subscribe as you normally do:
let center = NSNotificationCenter.defaultCenter()
let mainQueue = NSOperationQueue.mainQueue()
self.localeChangeObserver = center.addObserverForName(NSCurrentLocaleDidChangeNotification, object: nil, queue: mainQueue) { (note) in
print("The user's locale changed to: \(NSLocale.currentLocale().localeIdentifier)")
}
Remove the observer at some point of code.
NotificationCenter.default.removeObserver(self.localeChangeObserver) e.g. through a function or in deinit
Note: You'd still need to use [weak self] to avoid retain cycles.
To avoid a retain cycle, use a weak reference to self inside the block when self contains the observer as a strong reference.
Single subscribe
Remove the observer immediately after the first time it gets a callback
let center = NSNotificationCenter.defaultCenter()
let mainQueue = NSOperationQueue.mainQueue()
var token: NSObjectProtocol?
token = center.addObserverForName("OneTimeNotification", object: nil, queue: mainQueue) { (note) in
print("Received the notification!")
center.removeObserver(token!)
}
Selector-based addObserver
If you use the selector-based add, self (there is no token) the observer. Having that said, you should avoid doing:
NotificationCenter.default.removeObserver(self)
because your code may not be the only code adding observers that involve the object. When removing an observer, remove it with the most specific detail possible. For example, if you used a name and object to register the observer, use removeObserver(_:name:object:) with the name and object.
It’s only safe to call removeObserver(something) in the deinit method, other than that don’t use it use removeObserver(_:name:object:) instead.
Calling removeObserver(self) is incorrect outside deinit, because you’d be removing all observations set for the object. Calling it inside deinit isn’t incorrect, but meaningless, because the object is to be deallocated immediately.
Set your observer object to current view controller.
From apple doc.s, object is
The object whose notifications the observer wants to receive; that is,
only notifications sent by this sender are delivered to the observer.
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification,
object: self,
queue: nil) { [weak self] notification in
guard let self = self else { return }
self.loadWeather(notification.object)
}
Removing observer from NotificationCenter
deinit {
NotificationCenter.default.removeObserver(self)
}
ANOTHER WAY
You can also make copy of Notification Observer object and remove it from NotificationCenter in deinit.
let notificationCenter = NotificationCenter.default
var loadWeatherObserver: NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
loadWeatherObserver = notificationCenter.addObserver(forName: UIApplication.didBecomeActiveNotification,
object: nil,
queue: nil) { [weak self] notification in
guard let self = self else { return }
self.loadWeather(notification.object)
}
}
deinit {
if (loadWeatherObserver != nil) {
notificationCenter.removeObserver(loadWeatherObserver!)
}
}

Observers don't get called using NotificationCenter Swift 4.0

I have a two ViewControllers: ViewController and SecondViewController.
I added an observer to this two ViewControllers. In ViewController I also defined an IBAction to post the notification. I handle the notification via a closure in both ViewControllers. But only the closure in the ViewController gets called. The closure (and even the whole code) in the SecondViewController does not get called (I checked with debugger). The closure only contains a print-statement.
Here is my Code
//ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
print("I'm the : \(type(of: self))")
}
}
#IBAction func sendNotification(_ sender: UIButton) {
let nc = NotificationCenter.default
nc.post(name: Notification.Name(rawValue:"MyNotification"), object: nil, userInfo: ["message":"Hello there!", "Date:":Date()])
}
}
The ScondViewController
//SecondViewController
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
print("I'm the: \(type(of: self))")
}
}
}
The closure in ViewController gets called but the closure in SecondViewController does not. Maybe the reason is that SecondViewController does not get initialized before I post the notification. But how would a solution look like?
Any help is appreciated.
If this is one-to-one relationship you can also use the Delegate pattern instead. Although you are right, the notification observer is not yet called because you do not initialise before the post. So there shouldn't be a reason for a function to be called in the SecondViewController.
So if you only need that to update a variable value, you can do that somewhere else in a Variables class where both ViewControllers have access.

iOS unable to remove Notification observer. Deinit not getting called

I have a UIView similar to the one you can see below:
class ViewTaskViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
subscribeToNotifications()
}
func subscribeToNotifications() {
let notification = NotificationCenter.default
notification.addObserver(forName: Notification.Name(rawValue: "TimerUpdated"), object: nil, queue: nil, using: handleUpdateTimer)
print("Subscribed to NotificationCenter in ViewTaskViewController")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("TUFU TUFU TUFU")
NotificationCenter.default.removeObserver(self)
}
deinit {
print("DENINT")
}
#objc func handleUpdateTimer(notification: Notification) {
if let userInfo = notification.userInfo, let timeInSeconds = userInfo["timeInSeconds"] as? Int {
withUnsafePointer(to: &self.view) {
print("We got timeeeeee \(timeInSeconds) \($0)")
}
//do something here....
}
}
}
The issue I am having is that I am unable to remove the observers from this particular UIView when the user hits the back button and returns to another viewController.
ViewWillDisppear is called but deinit is not called. The strange thing is that if we remove subscribeToNotifications() from viewDidLoad() then the deinit is called.
The other issue is related to a memory leak. As you can see in the screenshot below, when the view does subscribe to notifications and the user leaves/re-enters the view, the memory usage increase.
Now compare that to when the subscribeToNotifications() is commented out, there is no increase in memory usage and only one instance of the viewController.
The conclusion is that there seems to be a correlation between the notification subscription creation of a new instance of the UIView hence the deinit is not being called.
I'd like to find out if there is a way we can deinitialize the view and unsubscribe from the notification.
Please let me know if you need further information. :)
I've found the removeObserver() only works if you use this version of addObserver()
notification.addObserver(self, selector:#selector(self.handleUpdateTimer), name: Notification.Name(rawValue: "TimerUpdated"), object: nil)
I'm guessing with the original version you aren't actually indicating who the observer is.
As #Spads said you can use
NotificationCenter.default.addObserver(self, selector: #selector(subscribeToNotifications), name: NSNotification.Name(rawValue: "TimerUpdate"), object: nil)
or the one you already have.
you can remove your notification by it's name or it's reference
NotificationCenter.default.removeObserver(self, name: "TimerUpdate", object: nil)
if you declared your notification at the top of your class then you can directly pass the reference of your notification to be removed in your case notification
NotificationCenter.default.removeObserver(notification)
You should store your newly added observer in a opaque object (NSObjectProtocol) and then call NotificationCenter.default.removeObserver(self.nameOfObserver)

AVSpeechSynthsesizer on timer

If a switch is turned on, text-to-word spoken every x seconds. The switch is on the first view controller, and the speech occurs after a segue to the second view controller.
Code in the first view controller:
#IBAction func speakwords(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("speaknotif", object: speakwords)
Code in the second view controller:
verride func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("talk:"), name: "speaknotif", object: self.view.window)
func talk(notification: NSNotification){guard let count = notification.object else {return}
if Bool(TYPE_BOOL as! NSO) = "true"{
let speechsynth = AVSpeechSynthesizer()}
In your case, Notification Center was useless. Because you are calling post method before adding observer for that notification. So notification concept won't work there.
Instead of this, just set one Bool like "isSwitchSelected". And pass that value to next vc, check if the value is yes, then call func talk method.

Resources