代码之家  ›  专栏  ›  技术社区  ›  Vyachaslav Gerchicov

需要有关在iOS中请求通知权限的说明

  •  1
  • Vyachaslav Gerchicov  · 技术社区  · 7 年前

    Info about "authorization"

    Info about "requesting permission"

    问题是它们都需要在同一个代码中,但它们被分成两个独立的项目。因此,目前还不清楚如何同时处理它们,以及它们之间的区别(当然,除了输入参数)。

    我找到的代码只是按顺序调用这些函数:

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

    对吗?这些方法有什么区别?

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Marek J.    7 年前

    这个

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

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

    UIApplication.shared.registerForRemoteNotifications()
    

    根据 Docs

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

    //

    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()
    
    推荐文章