当我从内部ViewControlller请求通知权限时,通知处理停止了工作

时间:2017-11-18 16:07:13

标签: ios swift firebase

一旦应用程序开始工作,我正在使用AppDelegate向用户询问通知权限。然后我意识到这不是最好的用户体验。所以我将代码移动到自定义视图控制器,仅在需要时才请求许可。这是我的代码

public static func requestNofiticationPermission(completionHanlder : @escaping (Bool) -> Void){
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = UIApplication.shared.delegate as! AppDelegate

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]

        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (success, error) in
            completionHanlder(success)
        })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
    }

    UIApplication.shared.registerForRemoteNotifications()
}

AppDelegate代码

// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    handleNotification(userInfo: userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    handleNotification(userInfo: userInfo)
    completionHandler(UIBackgroundFetchResult.newData)
}

// print notification data
func handleNotification(userInfo: [AnyHashable: Any]){
    let gcmMessageIDKey = "gcm.message_id"
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    var body : String!
    var title : String?
    if let aps = userInfo["aps"] as? [String : Any] {
        if let alert = aps["alert"] as? [String : String] {
            body = alert["body"]
            title = alert["title"]
        }
    }

    print("title: \(title)")
    print("body: \(body)")
}

正如您所看到的,我在AppDelegate中保留了消息处理,并在像UIApplication.shared.delegate这样的代码中引用它。由于某种原因,它停止处理消息。功能没有被触发

0 个答案:

没有答案