【问题标题】:Need explanation about requesting permission for notifications in iOS需要有关在 iOS 中请求通知权限的说明
【发布时间】:2018-12-19 10:24:42
【问题描述】:

Info about "authorization"

Info about "requesting permission"

问题是它们都需要在相同的代码中,但它们被分成两篇单独的文章。所以不清楚如何同时处理它们,它们之间有什么区别(当然除了输入参数)。

我发现的代码只是顺序调用这些函数:

UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
  ...
})
UIApplication.shared.registerForRemoteNotifications()

正确吗?这些方法有什么区别?

附:根据文档,我也不能简单地将它们放在application:didFinishLoad: 中,因为应用程序不应该从第一次运行时就请求权限。

【问题讨论】:

    标签: ios swift push-notification unusernotificationcenter unusernotification


    【解决方案1】:

    这个

    UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
      ...
      // code here
    })
    

    询问用户是否接受实际会显示弹出窗口的接收通知,但这(用于非本地推送通知)

    UIApplication.shared.registerForRemoteNotifications()
    

    根据Docs

    调用此方法以启动与 Apple 的注册过程 推送通知服务。如果注册成功,应用调用 你的应用委托对象的 应用程序:didRegisterForRemoteNotificationsWithDeviceToken:方法 并将设备令牌传递给它。

    //

    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
    
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    
    application.registerForRemoteNotifications()
    

    【讨论】:

    • 从您的文档链接:If you want your app’s remote notifications to display alerts, play sounds, or perform other user-facing actions, you must request authorization to do so using the requestAuthorization(options:completionHandler:) method of UNUserNotificationCenter. 但他们没有描述如何调用它。我需要徽章/声音/横幅来通知,但如果是这样,如果我不使用application:didRegisterForRemoteNotificationsWithDeviceToken:,我应该打电话给registerForRemoteNotifications吗?
    猜你喜欢
    • 2017-07-31
    • 2019-08-17
    • 2017-02-12
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2016-12-17
    • 2018-03-27
    相关资源
    最近更新 更多