The following steps will guide us on how to develop an application in Swift that implements Local Notification.
Requirements are:
- Open xcode.
- Create a Single View Application, let's name it LocalNotification.
- Register for user notification.
- In the newly created project, open AppDelegate.swift
- Insert the lines below in: didFinishLaunchingWithOptions
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
UIUserNotificationType.Badge, categories: nil
))
- To show an alert view when we received a local notification, we need to override: didReceiveLocalNotification,
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("received local notification")
application.applicationIconBadgeNumber = 0
var alert = UIAlertView()
alert.title = "Alert"
alert.message = notification.alertBody
alert.addButtonWithTitle("Dismiss")
alert.show()
}
- To demo local push notification in our app, we override ViewController.swift viewDidLoad method. So open this file and paste the lines below:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 30)
localNotification.alertBody = "Hello World"
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = 1
//play a sound
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertAction = "View"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
- To test if our app works, open the app and let it open the view. Then open another app, or just hide our app. After 30 seconds you should received a push notification alert.
- Note that local notification only works on real iPhone device.
0 nhận xét:
Đăng nhận xét