无法使用 [UIApplication sharedApplication]。如何在 UIApplicationDelegate 之外注册通知?

Posted

技术标签:

【中文标题】无法使用 [UIApplication sharedApplication]。如何在 UIApplicationDelegate 之外注册通知?【英文标题】:Cannot use [UIApplication sharedApplication]. How can I register for notifications outside UIApplicationDelegate? 【发布时间】:2015-03-11 15:07:00 【问题描述】:

我正在编写一个带有 WatchKit 扩展的应用程序。

我以前可以使用[[UIApplication sharedApplication] registerForNotificationTypes:] 在 UIApplicationDelegate 之外注册通知。

[UIApplication sharedApplication] 现在在包含 WatchKit 扩展的项目中不可用。

我现在如何在 UIApplicationDelegate 之外注册通知?

为了清楚起见:我正在尝试在我的包含应用程序中注册通知,而不是 watchkit 扩展。

【问题讨论】:

【参考方案1】:

不允许 WatchKit 扩展发送通知。

请使用包含的应用来执行此功能,然后在 WatchKit 扩展中,您将能够显示和自定义通知的外观。

【讨论】:

当然可以,但是我需要在 ios 应用程序中注册通知,如果我使用嵌入式 WatchKit 扩展程序编译应用程序,[UIApplication sharedApplication] 不可用。 那么这个问题与WatchKit无关。无论如何,该方法在 iOS 8 中已被弃用。请使用:registerUserNotificationSettings【参考方案2】:

与任何 iOS 扩展*一样,作为 WatchKit 扩展目标一部分的代码(源文件)无法访问 sharedApplication 对象,因此您无法使用该对象上的任何方法。对于属于您的应用程序主要目标(而不是 WatchKit 扩展目标)的代码(源文件),您仍然可以使用以下调用

[[UIApplication sharedApplication] registerForNotificationTypes:]

因此,您可能正在从添加到 WatchKit 扩展目标中的某个源文件中使用此调用。

*App Extension Programming Guide

【讨论】:

从 WatchKit 2 开始,这不再正确。请参阅 ***.com/questions/36270738/…【参考方案3】:

从 WatchKit 2 开始,情况发生了很大变化。您现在可以access a shared delegate object in the WatchKit App Extension,通过访问WKExtensionDelegate,您可以访问六种与通知相关的方法:didReceiveRemoteNotification(_:)didReceiveLocalNotification(_:)handleActionWithIdentifier(_:forRemoteNotification:)handleActionWithIdentifier(_:forRemoteNotification:withResponseInfo:)handleActionWithIdentifier(_:forLocalNotification:),和handleActionWithIdentifier(_:forLocalNotification:withResponseInfo:)

请参阅Apple Documentation 了解更多信息。

【讨论】:

以上是关于无法使用 [UIApplication sharedApplication]。如何在 UIApplicationDelegate 之外注册通知?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 UIApplication.shared.open 在 iOS 上选择性地打开其他应用程序

在 iOS 扩展和应用程序之间使用 UIApplication.shared 共享 CocoaPod

`UIApplication.shared.canOpenURL(:)` 方法在 iOS 11.4(仅限 iPad 设备)上不起作用?

有没有办法为`UIApplication.shared`添加`if(iOSApplicationExtension)`条件

Swift/iOS13 - UIApplication.shared.delegate.window?.rootViewController?.present() 来自自定义类

swift `UIApplication.shared.isNetworkActivityIndi​​catorVisible`管理クラス(延迟非対応)