1. Disable 'Use Auto Layout' in the storyboard file inspector.
2. Drag a button to the storyboard and name it 'Start Notification'.
3. Control-drag the button to ViewController.swift:
@IBAction func myButton(sender: UIButton) {
}
4. Modify the code in ViewController.swift as below:
import UIKit
class ViewController: UIViewController {
@IBAction func myButton(sender: UIButton) {
var myNotification = UILocalNotification()
myNotification.applicationIconBadgeNumber = 1
myNotification.soundName = UILocalNotificationDefaultSoundName
myNotification.alertBody = "Alert!"
myNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
UIApplication.sharedApplication().scheduleLocalNotification(myNotification)
}
override func viewDidLoad() {
super.viewDidLoad()
}
5. Register notification types (user notification settings) by modifying the function application in AppDelegate.swift as below:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let myNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: myNotificationType, categories: nil))
return true
}
Note: registerForRemoteNotificationTypes is deprecated in iOS8. Use registerUserNotificationSettings instead.
Note: registerForRemoteNotificationTypes is deprecated in iOS8. Use registerUserNotificationSettings instead.
6. Run the app and see this alert window:
7. Press OK and see this:
8. Press 'Start Notification' button and press the Home key. Then the notification is displayed after the 'Start Notification' button is press for 5 sec:
9. The badge number becomes one.
10. Add the code below to AppDelegate:
10. Add the code below to AppDelegate:
func applicationWillEnterForeground(application: UIApplication) {
//This clears the badge number
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}
No comments:
Post a Comment