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

时间:2016-07-28 00:13:32

标签: ios swift notifications localnotification

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

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

在启用提醒之前,我不会要求用户获得本地通知的许可。之后,我必须检查,如果用户授予权限并安排通知,如果是这样。

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

我知道appdelegate消息'didRegisterUserNotificationSettings',这是在问题得到解答后发送的。一个想法是首先将通知存储在全局变量中,并在授予权限时对其进行计划。但是,如果通知最后没有安排,那将会执行太多的代码。

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

这是我在UISwitch'valueue changed'事件中的一段有问题的代码,它无法正常工作:

//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
    }

有没有人有想法? 提前谢谢

2 个答案:

答案 0 :(得分:1)

Closure

中声明AppDelegate
var userNotificationChanged: ((settings: UIUserNotificationSettings) -> Void)?

并在用户注册closure

时调用notification

您的AppDelegate didRegisterUserNotificationSettings将如下所示

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

现在,valueChanged UISwitch事件closure设置 (UIApplication.sharedApplication().delegate as! AppDelegate).userNotificationChanged = { (settings: UIUserNotificationSettings) -> Void in //Schedule your notification here } 并执行您所需的操作:

mainactivity

答案 1 :(得分:-1)

将这个简单的代码放在WHERE ( [DimManagedPopulation].[ManagedPopulationName].&[1044]&[LTC Lincoln Centers], { [DimAnchorDate].[Calender Year].&[2015], [DimAnchorDate].[Calendar Semester Des].[All], [DimAnchorDate].[Calendar Quarter Des].&[2013]&[Quarter1], [DimAnchorDate].[English Month Name Desc].[All] } );

didFinishLaunchingWithOptions