[英]Send and receive messages through NSNotificationCenter in swift?
I need a simple example program to send and receive a message through NSNotificationCenter in Swift? 我需要一个简单的示例程序来通过Swift中的NSNotificationCenter发送和接收消息? 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
}
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleRouteChange:", name: AVAudioSessionRouteChangeNotification, object: nil);
NSNotificationCenter.defaultCenter().postNotificationName(AVAudioSessionRouteChangeNotification, object: nil)
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.