向用户询问本地通知并在之后执行任务 - Swift 2.0

Ask user for local notifications and perform tasks afterwards - Swift 2.0

我在 SO 或其他地方找不到解决我的问题的帮助,所以我希望你们中的一些人能帮助我。

我正在尝试在我的 iOS 应用程序中实现提醒功能,该功能由用户自行启用。提醒是本地通知。

在用户启用提醒之前,我不会请求用户获得本地通知的权限。之后,我必须检查用户是否授予了权限,如果是,则安排通知。

这里的核心问题是代码不会停止执行“registerUserNotificationSettings”方法并等待即将到来的 UIAlertController 的结果。因此我无法在调用该方法后直接检查权限。 我也不想在第一次启动应用程序时请求许可,因为用户不知道为什么我的应用程序应该发送通知,而且我认为这对于第一次启动和可选功能来说太多了。

我知道 appdelegate 消息“didRegisterUserNotificationSettings”,它是在回答问题后发送的。一个想法是首先将通知存储在全局变量中,并在授予权限后对其进行调度。但是,如果最后甚至没有安排通知,那么将执行的代码太多了。

所以我正在寻找一些解决方案来征求用户的许可,然后决定是否创建和安排通知。

这是我在 UISwitch 的“值已更改”事件中出现问题的一段代码,它没有按预期工作:

//check if the app is allowed to send notifications or ask the user
    var settingTypes = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
    if (settingTypes?.contains(.Alert) == false) {
        let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)

//get NotificationSettings again after the user was asked 
    settingTypes = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
    }


//now check if if notifications are finally permitted
    if (settingTypes?.contains(.Alert) == true) {
        let notification = UILocalNotification()
        * create notification *
        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    }
    else {
        switchNotification.on = false
    }

有人有想法吗? 提前谢谢你

AppDelegate

中声明一个 Closure
var userNotificationChanged: ((settings: UIUserNotificationSettings) -> Void)?

并在用户注册 notification

时调用 closure

您的 AppDelegate didRegisterUserNotificationSettings 如下所示

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if (userNotificationChanged != nil) {
        userNotificationChanged!(settings: notificationSettings)
    }
}

现在在 UISwitchvalueChanged 事件中设置 closure 并在其中执行所需的操作:

    (UIApplication.sharedApplication().delegate as! AppDelegate).userNotificationChanged = { (settings: UIUserNotificationSettings) -> Void in

        //Schedule your notification here
    }

把这个简单的代码放在didFinishLaunchingWithOptions

if #available(iOS 8.0, *)
{

    if application.respondsToSelector("isRegisteredForRemoteNotifications")
    {

        let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])

        let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)

        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

}
else{
        let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
        application.registerForRemoteNotificationTypes(types)
}