我希望 iOS11 版本能够解决静默推送问题,该问题在 iOS 的最新 beta 和 GM 版本中。
目前我很难理解,为什么我没有收到任何静默推送消息,这实际上应该唤醒我的应用程序以在后台执行一些需要的任务。
在 iOS 10 中,我只使用后台获取功能并在我的 AppDelegate 中实现了“唤醒代码”,如下面的代码。
在 iOS 11 中,注册代码仍然可以正常工作,我的后端也将推送通知发送到 Apple DEV 服务器(沙箱)和 PROD 服务器(生产版本)。不幸的func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
是,静默推送通知永远不会调用该函数。
我真的错过了 iOS 11 的内容吗?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// .. some variables here ...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// register silent push notification in backend
application.registerForRemoteNotifications()
// ... some code here ...
// Set Background Fetch Intervall for background services / terminated app
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
// ... some code here ...
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
logger.log.debug("Device Token: \(token)")
let realm = RealmController()
let user = realm.getLoggedInUserObject()
// Send push token to server
if let user = user {
let email = user.email!
let serverController = ServerController.serverController
serverController.sendPushToken(token: token, email: email) { status in
if status == 201 {
// ... some code here ...
} else {
// ... some code here ...
}
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
logger.log.debug(error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
logger.log.debug(userInfo)
let aps = userInfo["aps"] as! [String: AnyObject]
if aps["content-available"] as? Int == 1 {
// .... some silent push tasks here ....
}
}
}