xcode 如何控制何时在 iOS 中提示用户推送通知权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30817069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:17:12  来源:igfitidea点击:

How to control when to prompt user for push notification permissions in iOS

iosxcodeswiftparse-platform

提问by Simon

I've built an application for iPhone using Swift and Xcode 6, and the Parse framework to handle services.

我已经使用 Swift 和 Xcode 6 以及 Parse 框架为 iPhone 构建了一个应用程序来处理服务。

While following the Parse tutorials on how to set up push notifications, the instructions advised that I put the push notifications in the App Delegate file.

在遵循有关如何设置推送通知的 Parse 教程时,说明建议我将推送通知放在 App Delegate 文件中。

This is the code that I have added to the App Delegate file...

这是我添加到 App Delegate 文件中的代码...

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var pushNotificationsController: PushNotificationController?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

         // Register for Push Notifications
        self.pushNotificationsController = PushNotificationController()

        if application.respondsToSelector("registerUserNotificationSettings:") {
            println("registerUserNotificationSettings.RegisterForRemoteNotificatios")
            let userNotificationTypes: UIUserNotificationType = (.Alert | .Badge | .Sound)
            let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        }

        return true;
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        println("didRegisterForRemoteNotificationsWithDeviceToken")
        let installation = PFInstallation.currentInstallation()
        installation.setDeviceTokenFromData(deviceToken)
        installation.saveInBackground()
    }
}

So what happens is that as soon as the application is launched for the first time, the user is prompted to grant these permissions.

因此,当应用程序第一次启动时,就会提示用户授予这些权限。

What I want to do, is only prompt for these permissions after a certain action has taken place (ie, during a walkthrough of the features of the app) so I can provide a little more context on why we would want them to allow push notifications.

我想要做的,只是在发生特定操作后(即在应用程序功能演练期间)提示这些权限,因此我可以提供更多关于为什么我们希望它们允许推送通知的上下文.

Is it as simple as just copying the below code in the relevant ViewController where I will be expecting to prompt the user?

是否就像在相关的 ViewController 中复制以下代码一样简单,我希望在其中提示用户?

// In 'MainViewController.swift' file

func promptUserToRegisterPushNotifications() {
        // Register for Push Notifications
        self.pushNotificationsController = PushNotificationController()

        if application.respondsToSelector("registerUserNotificationSettings:") {
            println("registerUserNotificationSettings.RegisterForRemoteNotificatios")
            let userNotificationTypes: UIUserNotificationType = (.Alert | .Badge | .Sound)
            let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        }
}

func application(application: UIApplication,    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        println("didRegisterForRemoteNotificationsWithDeviceToken")
        let installation = PFInstallation.currentInstallation()
        installation.setDeviceTokenFromData(deviceToken)
        installation.saveInBackground()
}

thanks!

谢谢!

采纳答案by LinusGeffarth

The answer is simple. If you want the user to be prompted some other time, for instance on a button press then simply move the code regarding the request into that function (or call promptUserToRegisterPushNotifications()from somewhere else).

答案很简单。如果您希望在其他时间提示用户,例如在按下按钮时,只需将有关请求的代码移动到该函数中(或promptUserToRegisterPushNotifications()从其他地方调用)。

To get a hold of the applicationvariable outside the AppDelegate, simply do this:

application在 AppDelegate 之外获取变量,只需执行以下操作:

let application = UIApplication.shared

Hope that helps :)

希望有帮助:)

回答by Marie Amida

This is for Swift 2. I have placed promptUserToRegisterPushNotifications() in MainViewController.swift, but I have left didRegisterForRemoteNotificationsWithDeviceToken in AppDelegate because it didn't work when I place it on the same MainViewController.swift.

这是针对 Swift 2 的。我在 MainViewController.swift 中放置了 promptUserToRegisterPushNotifications(),但我将 didRegisterForRemoteNotificationsWithDeviceToken 留在了 AppDelegate 中,因为当我将它放置在同一个 MainViewController.swift 时它不起作用。

// In 'MainViewController.swift' file
func promptUserToRegisterPushNotifications() {
    // Register for Push Notifications

    let application: UIApplication = UIApplication.sharedApplication()

    if application.respondsToSelector(#selector(UIApplication.registerUserNotificationSettings(_:))) {
        print("registerUserNotificationSettings.RegisterForRemoteNotificatios")

        let notificationSettings = UIUserNotificationSettings(
            forTypes: [.Badge, .Sound, .Alert], categories: nil)
        application.registerUserNotificationSettings(notificationSettings) // Register for Remote Push Notifications
        application.registerForRemoteNotifications()
    }
}


// In AppDelegate
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "deviceToken")

    print("Device Token:", tokenString)

}

回答by Prakash Raj

This is method I have written in the code and works fine once it called on launch (didFinishLaunch)

这是我在代码中编写的方法,一旦它在启动时调用就可以正常工作(didFinishLaunch)

class func registerNotification() {
    if #available(iOS 10.0, *) {
        // push notifications
        UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .badge]) {
            (granted, error) in
            if (granted) {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }

        let center  = UNUserNotificationCenter.current()
        center.delegate = AppManager.appDel()
        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if error == nil {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    } else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}