【发布时间】:2015-06-13 09:26:08
【问题描述】:
我使用 Swift 和 Xcode 6 以及 Parse 框架为 iPhone 构建了一个应用程序来处理服务。
在遵循有关如何设置推送通知的 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()
}
谢谢!
【问题讨论】:
-
是的,您可以简单地移动该代码以在适当的时间执行:)
-
感谢 SomeGuy!我会在我回到我的项目后立即尝试,如果我需要更多帮助,请回来报告。谢谢!
-
如何获取应用程序:UIApplication到另一个viewController中?
-
嘿,如果有帮助,您介意接受我的回答吗? :)
-
@denislexic,我所做的是在 viewController 中声明了一个全局变量,例如
let application: UIApplication = UIApplication.sharedApplication()。这似乎对我有用。 :)
标签: ios xcode swift parse-platform