在我的应用程序中,我希望在用户连接某些无线音频播放器(耳机、扬声器等)时收到通知...
除了在连接时写入日志之外,该应用程序目前实际上什么都不做。现在,虽然应用程序在前台,但我正确地看到了所有日志,但是一旦我进入主屏幕,并尝试连接/断开某些东西,我就不再看到日志了。应用在后台时是否可以收到通知?
我也想收到通知,即使应用程序已完全关闭 - 我认为这是不可能的。 (如果是这样,那么即使关闭了 WhatsApp 等应用程序,它们如何仍能收到通知)。
这是我创建通知的方式:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setupNotifications()
return true
}
func setupNotifications() {
print("AppDeleagte: setupNotification")
NotificationCenter.default.addObserver(self,
selector: #selector(handleRouteChange),
name: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance())
}
@objc func handleRouteChange(notification: NSNotification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
return
}
switch reason {
case .newDeviceAvailable:
let session = AVAudioSession.sharedInstance()
print("AppDelegate: handleRouteChange () --> new device available")
for output in session.currentRoute.outputs {
// headphonesConnected = true
print("output port type = ", output.portType, " output port name = ", output.portName)
}
case .oldDeviceUnavailable:
print("AppDelegate: handleRouteChange () --> old device unavailable")
if let previousRoute =
userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
for output in previousRoute.outputs {
// headphonesConnected = false
}
}
default: ()
}
}