no

How to implement local notification in Swift

The following steps will guide us on how to develop an application in Swift that implements Local Notification. Requirements are: Mac ...

The following steps will guide us on how to develop an application in Swift that implements Local Notification.

Requirements are:

  • Mac
  • Xcode6 - BetaX
  • iOS8

Steps

  1. Open xcode.
  2. Create a Single View Application, let's name it LocalNotification.
  3. Register for user notification.
    1. In the newly created project, open AppDelegate.swift
    2. Insert the lines below in: didFinishLaunchingWithOptions
    3. application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
                  UIUserNotificationType.Badge, categories: nil
                  ))
      
  4. To show an alert view when we received a local notification, we need to override: didReceiveLocalNotification,
  5. 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()
    }
    
  6. To demo local push notification in our app, we override ViewController.swift viewDidLoad method. So open this file and paste the lines below:
  7. 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)
    }
    
  8. 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.
  9. Note that local notification only works on real iPhone device.

Related

xcode 3145141544082908925

Post a Comment Default Comments

item