【问题标题】:How an I prevent the UIAlertView from appearing when a push notification is received while the app is in the foreground?当应用程序处于前台时收到推送通知时,如何防止 UIAlertView 出现?
【发布时间】:2015-04-12 02:57:25
【问题描述】:
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)
        }
    }

【问题讨论】:

    标签: ios swift parse-platform push-notification


    【解决方案1】:

    如果调用didReceiveRemoteNotification委托方法

    1. 收到通知时用户在应用程序中,或
    2. 用户在应用外收到通知后会参与其中。

    您可以选择使用application.applicationState 处理通知的方式,您已经这样做了。来自How to respond to push notification view if app is already running in the background

    您可以判断您的应用是刚刚被带到前台还是 不在application:didReceiveRemoteNotification: 使用这个位 代码:

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

    “不活动”不会打印,因为UIApplicationStateInactive (UIApplicationState.Inactive) 是以下情况:

    应用正在前台运行,但未接收事件。这可能是由于中断或应用程序在后台转换或从后台转换的结果。 Source

    所以,你真正要找的是UIApplicationState.Background

    if application.applicationState == UIApplicationState.Background {
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(data, block:nil)
    }
    

    那么,这解决了从后台打开的问题,但是当用户在应用中收到通知时呢?您不希望出现不和谐的弹出窗口,因此禁用它的方法是摆脱它的来源,PFPush.handlePush()

    handlePush: 所做的只是创建警报视图并将其呈现给用户,因此删除它不会影响其他任何事情:

    应用处于活动状态时的推送通知默认处理程序,可用于在应用处于后台或未运行时模拟 iOS 推送通知的行为。
    Source

    就是这样 - 只需将其删除,就不会出现警报视图。

    如果您想增加徽章计数,您仍然可以:

    if userInfo.objectForKey("badge") {
        let badgeNumber: Int = userInfo.objectForKey("badge").integerValue
        application.applicationIconBadgeNumber = badgeNumber
    }
    

    【讨论】:

    • @TIMEX 没问题;我很高兴能帮上忙。
    • 我是否需要检查 application:didFinishLaunchingWithOptions 中的通知?解析文档说我也需要处理这个问题。
    • @TIMEX 仅当您想配置用户通过推送通知打开您的应用程序后会发生什么。见parse.com/questions/…parse.com/questions/…
    • 但我认为您的第一部分代码解决了它?我能够使用此获取推送通知信息:if ( application.applicationState == UIApplicationStateActive ) // app was already in the foreground else // app was just brought from background to foreground
    • @TIMEX 我相信你可以做到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2017-05-11
    • 2020-12-23
    • 2017-06-26
    • 1970-01-01
    相关资源
    最近更新 更多