RequestAuthorization用于在didFinishLaunchingWithOptions之外推送

时间:2016-11-03 19:06:26

标签: ios swift3 ios10

对于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]?) - >布尔

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

2 个答案:

答案 0 :(得分:3)

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

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

并记住

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

答案 1 :(得分: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
            }
        }
    }
}