2014-12-05 65 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