Search code examples
swiftdateios8notificationspicker

Swift- Pushing notifications at a user selected time


How can I make a user choose a time by using a date picker and then send the user a local notification?


Solution

  • here is a simple code to schedule a local notification in swift:

    let calendar: NSCalendar = NSCalendar.currentCalendar()
    
    let fireDateOfNotification: NSDate = //The date which was picked from the picker
    
    var notification = UILocalNotification()
    notification.timeZone = NSTimeZone.localTimeZone()
    notification.alertBody = "ALERT STRING"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.fireDate = fireDateOfNotification
    notification.userInfo = ["UUID": "NotificationID"] //id for the local notification in case you want to cancel it
    
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
    

    and if you want to cancel a local notification you should use the following function:

    func cancelLocalNotificationsWithUUID(uuid: Int) {
            for item in UIApplication.sharedApplication().scheduledLocalNotifications {
                let notification = item as! UILocalNotification
                if let notificationUUID = notification.userInfo?["UUID"] as? Int {
    
                    if notificationUUID == uuid {
                        UIApplication.sharedApplication().cancelLocalNotification(notification)
                    }
    
                }
            }
        }
    

    I hope this helps.