在视图中安排本地通知确实加载方法

时间:2015-12-10 18:11:39

标签: ios iphone swift notifications ios9

我是一个快速编程的菜鸟,我正面临着一个问题。我正在尝试每天在同一时间安排本地通知,这没有用户安排它。一些重复间隔方法如何为我提供更多的通知。所以我现在不知道发生了什么。基本上我想要的是正确安排通知并以正确的方式调用调度方法。

这是我的视图控制器方法,我调用通知

      override func viewDidLoad() {
      super.viewDidLoad()
      notificar.scheduleNotification("message")     
}

这是通知助手类

class NotificationHelper {

static func askPermission() {

    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}



 func scheduleNotification(InputUser:String) {

    let now: NSDateComponents = NSCalendar.currentCalendar().components([.Hour, .Minute], fromDate: NSDate())

    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let date = cal.dateBySettingHour(now.hour, minute: now.minute + 1, second: 0, ofDate: NSDate(), options: NSCalendarOptions())
    let reminder = UILocalNotification()
    reminder.fireDate = date
    reminder.alertBody = InputUser
    reminder.alertAction = "Cool"
    reminder.soundName = "sound.aif"
    reminder.repeatInterval = NSCalendarUnit.Minute




    UIApplication.sharedApplication().scheduleLocalNotification(reminder)

    print("Firing at \(now.hour):\(now.minute+1)")
}

这是我的应用代表

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.


    NotificationHelper.askPermission()

    return true
}

正如你所看到的,在代码中我每分钟都会调用通知重复间隔,但是一旦通知被调用,我就会连续收到一堆5个通知,而不是单个通知。

请任何想法,我将非常感激。抱歉我的英语。 谢谢:))

1 个答案:

答案 0 :(得分:0)

您必须首先删除本地通知,然后在此处添加一个新通知代码。

var app: UIApplication = UIApplication.sharedApplication()
var eventArray: [AnyObject] = app.scheduledLocalNotifications()
for oneEvent: UILocalNotification in eventArray 
{
    var userInfoCurrent: [NSObject : AnyObject] = oneEvent.userInfo
    var uid: String = "\(userInfoCurrent["name"])"
// here give the name of your local notification.
    if (uid == obj["name"]) 
    {
        //Cancelling local notification
        app.cancelLocalNotification(oneEvent)
    }
}