当应用程序处于前台时收到推送通知时,我如何防止 UIAlertView 出现?
How an I prevent the UIAlertView from appearing when a push notification is received while the app is in the foreground?
var data = {
alert: "Your driver is here!",
sound: "ding.caf"
session_id: session.sessionId
}
parse.Push.send({
channels: ['user_id-2'],
data: data
},{
我正在发送带有警报的推送通知。当应用程序在后台时,它工作正常 – 我收到警报。
但是,当我的应用程序在前台运行时,UIAlertView
仍然会弹出,这对用户来说非常不和谐,当他们正在使用它时突然弹出一个警告。
如何在应用程序处于前台状态时禁用此功能?这是我在 Swift 中的全部代码。不过,我仍然想访问 JSON。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let center = NSNotificationCenter.defaultCenter()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().idleTimerDisabled = true
Parse.setApplicationId("SOMEID", clientKey: "SOMEKEY")
// Register for Push Notitications
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
application.registerForRemoteNotificationTypes(types)
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
println("Push notifications are not supported in the iOS Simulator.")
} else {
println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification data: [NSObject : AnyObject]) {
PFPush.handlePush(data)
var dat = JSON(data)
println("dat") //yes, we got a notification. this alerts even in foreground, which it shouldn't.
if application.applicationState == UIApplicationState.Inactive {
println("Inactive - this never prints")
PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(data, block:nil)
}
}
如果
调用didReceiveRemoteNotification
委托方法
- 收到通知时用户正在应用程序中,或者
- 用户在应用外收到通知后参与其中。
您可以使用 application.applicationState
选择如何处理通知,您已经完成了。来自 How to respond to push notification view if app is already running in the background:
You can tell whether your app was just brought to the foreground or
not in application:didReceiveRemoteNotification:
using this bit of
code:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if ( application.applicationState == UIApplicationStateActive )
// app was already in the foreground
else
// app was just brought from background to foreground
...
}
"Inactive" 不打印,因为 UIApplicationStateInactive
(UIApplicationState.Inactive
) 是以下情况为真时的情况:
The app is running in the foreground but is not receiving events. This might happen as a result of an interruption or because the app is transitioning to or from the background.
Source
那么,您实际要找的是 UIApplicationState.Background
:
if application.applicationState == UIApplicationState.Background {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(data, block:nil)
}
那么,这解决了从后台打开的问题,但是当用户在应用程序中收到通知时呢?你不想要刺耳的弹出窗口,所以禁用它的方法是摆脱它的来源,PFPush.handlePush()
。
handlePush:
所做的只是创建警报视图并将其呈现给用户,因此删除它不会影响任何其他内容:
A default handler for push notifications while the app is active that could be used to mimic the behavior of iOS push notifications while the app is backgrounded or not running.
Source
就是这样 - 只需将其删除,就不会出现警报视图。
如果您想增加徽章数量,您仍然可以:
if userInfo.objectForKey("badge") {
let badgeNumber: Int = userInfo.objectForKey("badge").integerValue
application.applicationIconBadgeNumber = badgeNumber
}
var data = {
alert: "Your driver is here!",
sound: "ding.caf"
session_id: session.sessionId
}
parse.Push.send({
channels: ['user_id-2'],
data: data
},{
我正在发送带有警报的推送通知。当应用程序在后台时,它工作正常 – 我收到警报。
但是,当我的应用程序在前台运行时,UIAlertView
仍然会弹出,这对用户来说非常不和谐,当他们正在使用它时突然弹出一个警告。
如何在应用程序处于前台状态时禁用此功能?这是我在 Swift 中的全部代码。不过,我仍然想访问 JSON。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let center = NSNotificationCenter.defaultCenter()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().idleTimerDisabled = true
Parse.setApplicationId("SOMEID", clientKey: "SOMEKEY")
// Register for Push Notitications
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
application.registerForRemoteNotificationTypes(types)
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
println("Push notifications are not supported in the iOS Simulator.")
} else {
println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification data: [NSObject : AnyObject]) {
PFPush.handlePush(data)
var dat = JSON(data)
println("dat") //yes, we got a notification. this alerts even in foreground, which it shouldn't.
if application.applicationState == UIApplicationState.Inactive {
println("Inactive - this never prints")
PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(data, block:nil)
}
}
如果
调用didReceiveRemoteNotification
委托方法
- 收到通知时用户正在应用程序中,或者
- 用户在应用外收到通知后参与其中。
您可以使用 application.applicationState
选择如何处理通知,您已经完成了。来自 How to respond to push notification view if app is already running in the background:
You can tell whether your app was just brought to the foreground or not in
application:didReceiveRemoteNotification:
using this bit of code:- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { if ( application.applicationState == UIApplicationStateActive ) // app was already in the foreground else // app was just brought from background to foreground ... }
"Inactive" 不打印,因为 UIApplicationStateInactive
(UIApplicationState.Inactive
) 是以下情况为真时的情况:
The app is running in the foreground but is not receiving events. This might happen as a result of an interruption or because the app is transitioning to or from the background. Source
那么,您实际要找的是 UIApplicationState.Background
:
if application.applicationState == UIApplicationState.Background {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(data, block:nil)
}
那么,这解决了从后台打开的问题,但是当用户在应用程序中收到通知时呢?你不想要刺耳的弹出窗口,所以禁用它的方法是摆脱它的来源,PFPush.handlePush()
。
handlePush:
所做的只是创建警报视图并将其呈现给用户,因此删除它不会影响任何其他内容:
A default handler for push notifications while the app is active that could be used to mimic the behavior of iOS push notifications while the app is backgrounded or not running.
Source
就是这样 - 只需将其删除,就不会出现警报视图。
如果您想增加徽章数量,您仍然可以:
if userInfo.objectForKey("badge") {
let badgeNumber: Int = userInfo.objectForKey("badge").integerValue
application.applicationIconBadgeNumber = badgeNumber
}