简体   繁体   English

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

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

I've built an application for iPhone using Swift and Xcode 6, and the Parse framework to handle services. 我使用Swift和Xcode 6构建了一个iPhone应用程序,并使用Parse框架来处理服务。

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! 谢谢!

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 application variable outside the AppDelegate, simply do this: 要在AppDelegate外部保留application变量,只需执行以下操作:

let application = UIApplication.shared

Hope that helps :) 希望有帮助:)

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(),但我在AppDelegate中保留了didRegisterForRemoteNotificationsWithDeviceToken,因为当我将它放在同一个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)

}

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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 本地反应如何控制何时在IOS中提示用户输入推送通知权限 - react native How to control when to prompt user for push notification permissions in IOS 如何确定在iOS safari上何时提示用户位置权限? - How is it determined when to prompt user location permissions on iOS safari? 如何控制Netmera ios sdk何时提示“推送通知”权限? - How to control when Netmera ios sdk will prompt Push notifications permission? 用户在iOS中向上滑动推送通知时如何执行操作 - How to perform an action when a user slides up a push notification in iOS 如何在iOS之前检查用户是否已经看过推送通知权限警报视图? - How to check whether user has seen the push notification permissions alert view before in iOS? apns-如何提示用户仅在相关时启用推送通知? - apns - how to prompt the user to enable push notification only when it becomes relevant? 如何以编程方式检测 ios 推送通知权限/设置 - How to detect ios push notification permissions/settings programmatically 如何在iOS的Google Play游戏服务中禁用推送通知权限? - How to disable push notification permissions in Google Play Games Services on iOS? 如何在iOS模拟器中重置推送通知权限? - How do I reset push notification permissions in iOS simulator? 当用户拒绝推送授权时,ios静默推送通知 - ios silent push notification when user denies Push Authorization
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM