我使用Swift和Xcode 6构建了一个iPhone应用程序,并使用Parse框架来处理服务 .
在关于如何设置推送通知的Parse教程之后,指示建议我将推送通知放在App Delegate文件中 .
这是我添加到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()
}
}
所以会发生的情况是,第一次启动应用程序时,系统会提示用户授予这些权限 .
我想要做的只是在某个动作发生后(即,在应用程序功能的演练期间)提示这些权限,所以我可以提供更多关于为什么我们希望它们允许推送通知的上下文 .
是否只是在相关的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()
}
谢谢!
3 回答
答案很简单 . 如果您希望在其他时间提示用户,例如按下按钮,则只需将有关请求的代码移动到该功能中(或从其他地方调用
promptUserToRegisterPushNotifications()
) .要在AppDelegate外部保留
application
变量,只需执行以下操作:希望有帮助:)
这是针对Swift 2.我在MainViewController.swift中放置了promptUserToRegisterPushNotifications(),但我在AppDelegate中保留了didRegisterForRemoteNotificationsWithDeviceToken,因为当我将它放在同一个MainViewController.swift上时它不起作用 .
这是我在代码中编写的方法,一旦调用启动就会正常工作(didFinishLaunch)