静默推送通知与普通推送通知
Silent push notification vs. normal push notifications
我通过 PHP 推送通知从我的网站空间发送到我的 swift 2 应用程序。
我这样做是:
$body['aps'] = array('alert' => 'HELLO', 'badge' => 1, 'sound' => 'default');
现在我也想使用静默推送通知。
我了解到,我可以像这样发送静默推送:
$body['aps'] = array('content-available' => 1);
在我的应用委托中,我在收到静默推送后做了一些事情。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("DO SOMETHING IN THE BACKGROUND")
handler(UIBackgroundFetchResult.NewData)
}
return
}
这很好用。
但现在的问题是,如果我也发送正常推送,每次都会出现此打印。
这是不正确的。打印 "DO SOMETHING IN THE BACKGROUND" 应该只在收到静默推送时执行。
我做错了什么?
按以下方式修改您的代码:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
if let apsValue = userInfo["aps"] as? NSDictionary {
if (apsValue["content-available"] as? Int == 1){
print("DO SOMETHING IN THE BACKGROUND")
handler(UIBackgroundFetchResult.NewData)
}
}
return
}
现在您的操作项每次都在执行,但上面的代码会将其过滤掉,以便它仅在有静默推送时执行(如您所知,由 content available = 1 标志指示。 )
我通过 PHP 推送通知从我的网站空间发送到我的 swift 2 应用程序。 我这样做是:
$body['aps'] = array('alert' => 'HELLO', 'badge' => 1, 'sound' => 'default');
现在我也想使用静默推送通知。 我了解到,我可以像这样发送静默推送:
$body['aps'] = array('content-available' => 1);
在我的应用委托中,我在收到静默推送后做了一些事情。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("DO SOMETHING IN THE BACKGROUND")
handler(UIBackgroundFetchResult.NewData)
}
return
}
这很好用。 但现在的问题是,如果我也发送正常推送,每次都会出现此打印。
这是不正确的。打印 "DO SOMETHING IN THE BACKGROUND" 应该只在收到静默推送时执行。
我做错了什么?
按以下方式修改您的代码:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
if let apsValue = userInfo["aps"] as? NSDictionary {
if (apsValue["content-available"] as? Int == 1){
print("DO SOMETHING IN THE BACKGROUND")
handler(UIBackgroundFetchResult.NewData)
}
}
return
}
现在您的操作项每次都在执行,但上面的代码会将其过滤掉,以便它仅在有静默推送时执行(如您所知,由 content available = 1 标志指示。 )