2
votes

I need a simple example program to send and receive a message through NSNotificationCenter in Swift? Im using core audio and I need to notify my app if the head phones are removed while I am playing audio. I don't know if I should add the observer in the app delegate or in my view since I have to keep playing audio in background.

This is the function that I use to control the route change to know if the headphones are removed.

-(void)handleRouteChange:(NSNotification *)notif
{
   NSDictionary *dict = notif.userInfo;
   AVAudioSessionRouteDescription *routeDesc = dict[AVAudioSessionRouteChangePreviousRouteKey];
   AVAudioSessionPortDescription *prevPort = [routeDesc.outputs objectAtIndex:0];
   if ([prevPort.portType isEqualToString:AVAudioSessionPortHeadphones]) {
        //Head phone removed
      }
 }
2
for swift 2.0 and swift 3.0 check stackoverflow.com/questions/27315228/…Sahil

2 Answers

3
votes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleRouteChange:", name: AVAudioSessionRouteChangeNotification, object: nil);
NSNotificationCenter.defaultCenter().postNotificationName(AVAudioSessionRouteChangeNotification, object: nil)
2
votes

To create a notification

let thisNotification = NSNotification(name: "createdNotification", object: nil)
NSNotificationCenter.defaultCenter().postNotification(thisNotification)

To observe for notifications

NSNotificationCenter.defaultCenter().addObserver(self, selector:"onCreatedNotification", name:"createdNotification", object: nil)
func onCreatedNotification(notification: NSNotification) {
    print("Notification received")
}