2014-12-05 136 views
2

我需要一个简单的示例程序来通过NSNotificationCenter在Swift中发送和接收消息? 即时通讯使用核心音频,我需要通知我的应用程序,如果在播放音频时头部手机被移除。我不知道是否应该将观察者添加到应用程序委托或我的视图中,因为我必须继续在后台播放音频。通过NSNotificationCenter在swift中发送和接收消息?

这是我用来控制路线变化以了解耳机是否被移除的功能。

-(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 
     } 
} 
+0

用于迅速2.0和3.0迅速检查http://stackoverflow.com/questions/27315228/ send-and-receive-messages-through-nsnotificationcenter-in-swift?rq = 1 – Sahil 2017-02-01 13:07:03

回答

1

创建通知

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

观察用于通知

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

感谢这帮助我弄清楚,唯一的改变是当你添加一个观察者时,这个名字是一个字符串。 – DrCachetes 2014-12-05 14:58:30

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

对代码的一小部分解释只会回答最多的答案呃更有帮助。 – Trilarion 2014-12-05 14:13:02