iPhone如何以编程方式访问通知中心

2024-01-04

根据苹果指南:

如果在运行 iOS 的设备上点击应用程序图标,应用程序将调用相同的方法,但不提供有关通知的信息。如果在运行的计算机上单击应用程序图标

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html#//apple_ref/doc/uid/TP40008194 https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html#//apple_ref/doc/uid/TP40008194

据我所知,点击应用程序图标时似乎无法检测到通知。

所以我尝试以编程方式检索通知中心,但这似乎也是不可能的。

是否无法以编程方式检索通知中心?

我想做的是检测是否收到通知,即使应用程序处于后台也是如此。


是否无法以编程方式检索通知中心?

不,任何公共 API 都不可能做到这一点。

您的应用程序不知道通知中心的当前状态,因为它们是两个解耦的实体。

无论如何,正如 AdamG 所指出的,在 iOS 7 中你可以实现

application:didReceiveRemoteNotification:fetchCompletionHandler:

其中,根据文档 https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/application%3adidReceiveRemoteNotification%3afetchCompletionHandler%3a,无论应用程序的状态如何(因此即使它没有运行或在后台)都会被调用。

为了使用它,您必须支持remote-notification背景模式。就是这样:

在 Xcode 5 及更高版本中,您可以从项目设置的“功能”选项卡中声明应用程序支持的后台模式。启用后台模式选项会将 UIBackgroundModes 键添加到应用程序的 Info.plist 文件中。选择一个或多个复选框会将相应的背景模式值添加到该键。

现在,虽然您仍然无法以编程方式访问通知中心,但您可以跟踪通知的到来。

模拟的实现如下:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Hey we got a notification!
    // Now we have 30 seconds to do whatever we like...
    // ...and then we have to call the completion handler
    completionHandler(UIBackgroundFetchResultNoData);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iPhone如何以编程方式访问通知中心 的相关文章

随机推荐