我已经使用
Swift和Xcode 6构建了一个应用程序,并且使用了Parse框架来处理服务.
在遵循关于如何设置推送通知的Parse教程之后,该指令表明我将推送通知放在App Delegate文件中.
这是我已经添加到App代理文件的代码…
@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()
}
}
那么会发生什么呢,一旦应用程序第一次启动,就会提示用户授予这些权限.
我想做什么,只是在一些动作发生之后才提示这些权限(即在应用程序的功能演练期间),所以我可以提供一些更多的上下文,为什么我们希望他们允许推送通知.
是否只需复制相关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()
}
谢谢!
解决方法
答案很简单如果您希望在其他时间提示用户,例如按下按钮,请将有关请求的代码简单地移动到该函数中(或从其他地方调用promptUserToRegisterPushNotifications()).
希望有帮助:)