我正在尝试在我的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"
}