【问题标题】:RequestAuthorization for push outside the didFinishLaunchingWithOptions在 didFinishLaunchingWithOptions 之外进行推送的 RequestAuthorization
【发布时间】:2017-03-17 12:05:33
【问题描述】:

对于 ios 10,我使用它来注册推送通知:

Registering for Push Notifications in Xcode 8/Swift 3.0?

有没有办法在 appdelegate 和 func 应用程序之外请求 requestAuthorization(options:[.badge, .alert, .sound]) (_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) - > 布尔

我问的原因是因为我不想在用户使用应用程序一段时间后显示推送通知的弹出窗口。有什么想法吗?

【问题讨论】:

  • 你可以在任何地方调用它

标签: ios swift3 ios10


【解决方案1】:

就像@dan 所说,没有必要在AppDelegate 中请求通知权限。你可以在任何你想去的地方做。这就是您可能正在为此做的事情。

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
    if error == nil {
        if success {
            print("Permission granted")
            // In case you want to register for the remote notifications
            let application = UIApplication.shared
            application.registerForRemoteNotifications()
        } else {
            print("Permission denied")
        }
    } else {
        print(error)
    }
}

记住

  1. 导入您使用此代码的UserNotifications 框架。
  2. 如果您注册远程通知,您需要在您的AppDelegate 中实现didRegisterForRemoteNotificationsWithDeviceToken 方法

【讨论】:

  • 但是在请求用户授权之前,我可以先拨打UIApplication.shared.registerForRemoteNotifications()获取token吗?还是要等用户授权后?
  • @NeoWang 如果用户尚未授予权限,此方法实际上会发起权限请求。请记住,未经许可,您将无法获得设备令牌。
  • 我认为在用户授予权限之前将设备令牌扔给应用程序
【解决方案2】:

对我来说,问题是一旦用户同意或拒绝,弹出窗口将不会再次显示。 所以我们必须在之后手动将用户重定向到设置。

以下是 Swift 中的代码:

@IBAction func userDidClickButton(_ sender: Any) {

    // initialise a pop up for using later
    let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
            // do something
            }
         }
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)

    // check the permission status
    UNUserNotificationCenter.current().getNotificationSettings () { settings in            
        switch settings.authorizationStatus {
        case .denied, .notDetermined:
            self.present(alertController, animated: true, completion: nil)
        case .authorized:
            // continue the stuff
            DispatchQueue.main.sync {
                // Update UI
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多