Search code examples
iosiphoneswiftnsnotificationcenternsnotifications

Send and receive messages through NSNotificationCenter in swift?


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

Solution

  • 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")
    }