【问题标题】:Send and receive messages through NSNotificationCenter in swift?通过 NSNotificationCenter 快速发送和接收消息?
【发布时间】:2015-02-03 14:01:11
【问题描述】:

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

这是我用来控制路线改变以知道耳机是否被移除的功能。

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

【问题讨论】:

标签: ios iphone swift nsnotificationcenter nsnotifications


【解决方案1】:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleRouteChange:", name: AVAudioSessionRouteChangeNotification, object: nil);
NSNotificationCenter.defaultCenter().postNotificationName(AVAudioSessionRouteChangeNotification, object: nil)

【讨论】:

  • 对代码的一点点解释只回答最常见的问题会使答案更有帮助。
【解决方案2】:

创建通知

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

【讨论】:

  • 感谢这帮助我弄清楚,唯一的错误是当您添加观察者时,名称是一个字符串。
猜你喜欢
  • 2011-01-12
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2018-03-31
相关资源
最近更新 更多