【发布时间】:2019-06-26 02:35:54
【问题描述】:
我正在使用 Parse SDK 处理推送通知的 IOS 应用程序。当我的背部处于后台时,我能够收到通知。现在,即使我的应用程序在前台,我也想收到通知。我已经搜索了很多代码,但它不适合我当前的 AppDelegate 类。
即使我的应用在前台,如何获得推送通知?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Thread.sleep(forTimeInterval: 3.0)
// Override point for customization after application launch.
let configuration = ParseClientConfiguration {
$0.applicationId = "asdasdasd"
$0.clientKey = "asdasdasdas"
$0.server = "https://parseapi.back4app.com"
}
Parse.initialize(with: configuration)
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .badge, .sound])
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else {
return
}
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
createInstallationOnParse(deviceTokenData: deviceToken)
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
}
}
我从同一个论坛找到了这个解决方案,但我无法将以下代码 sn-p 放入我当前的代码中:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
print("tap on on forground app",userInfo)
completionHandler()
}
【问题讨论】:
-
Unable 意味着我很困惑我从同一个论坛找到的上面的代码 sn-p 放在哪里以及如何放置。
标签: ios swift apple-push-notifications foreground