当应用在后台时,推送通知不显示

时间:2016-12-09 15:09:13

标签: ios swift firebase push-notification apple-push-notifications

我正在尝试在我的IOS应用中实施Firebase推送通知,但无法弄清楚当应用在后台时如何接收通知。

我使用print来显示通知,但它只在打开应用程序时打印通知。如果我在应用程序是后台时发送通知,则没有任何反应,但是一旦我重新打开应用程序就会打印消息。

以下是我的AppDelegate代码

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    registerForPushNotifications(application)
    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter
        .defaultCenter()
        .addObserver(self, selector: #selector(AppDelegate.tokenRefreshNotificaiton),
                     name: kFIRInstanceIDTokenRefreshNotification, object: nil)

    // Override point for customization after application launch.
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()
}


func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    sendNotification();

    print("===== didReceiveRemoteNotification ===== %@", userInfo)
}




func tokenRefreshNotificaiton(notification: NSNotification) {
    let refreshedToken = FIRInstanceID.instanceID().token()!
    print("InstanceID token: \(refreshedToken)")
    connectToFcm()
}

func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
        if (error != nil) {
            print("Unable to connect with FCM. \(error)")
        } else {
            print("Connected to FCM.")
        }
    }
}
func sendNotification() {
    let notification = UILocalNotification()
    let dict:NSDictionary = ["ID" : "your ID goes here"]
    notification.userInfo = dict as! [String : String]
    notification.alertBody = "title"
    notification.alertAction = "Open"
    notification.fireDate = NSDate()
    UIApplication.sharedApplication().scheduleLocalNotification(notification)


}


}

我也加入了我的info.plist

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

这是我发送的邮件的格式

{
  "to" : "",
  "notification" : {
  "body" : "",
  "title" : "",
},
  "content_available": true,
  "priority": "high"
}

2 个答案:

答案 0 :(得分:-1)

当您的应用关闭时,您无法接收推送通知数据。您应该将消息存储到服务器,而不是用户从那里到达消息

答案 1 :(得分:-1)

验证项目设置和“功能”是否已正确配置enter image description here

相关问题