UILocalNotificationサンプルソース

先日こんなお問い合わせをいただいた.


というわけで,iOS8に対応するUILocalNotificationのサンプルを作ってみました.


h3poteto/SampleLocalNotification · GitHub


めんどくさいので,デバイスのサイズは4インチ固定としています.

ViewController内のボタンをタップすることで,一分後のLocalNotificationを予約登録します.

あとは,アプリケーションをバックグラウンドにするなり,終了するなりしてみてください.
起動時には通知をキャッチするようになっています.


通知のキャッチはAppDelegateで,以下のように記述します.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
        
        if (launchOptions != nil) {
            var notification: UILocalNotification? = launchOptions![UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification
            if (notification != nil) {
                var alert = UIAlertView()
                alert.title = "ApplicationLaunch"
                alert.message = notification!.alertBody
                alert.addButtonWithTitle(notification!.alertAction!)
                alert.show()
            }
        }
        return true
    }

    /* 中略 */

        func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        if (application.applicationState == UIApplicationState.Active) {
            // foreground時のlocal notification
            var alert = UIAlertView()
            alert.title = "Foreground"
            alert.message = notification.alertBody
            alert.addButtonWithTitle(notification.alertAction!)
            alert.show()
        } else {
            // background時のlocal notification
            var alert = UIAlertView()
            alert.title = "Background"
            alert.message = notification.alertBody
            alert.addButtonWithTitle(notification.alertAction!)
            alert.show()
        }
    }
}

だいたい以前書いた通りに実装しています.


iOS8でUILocalNotificationの通知を受け取る - PartyIX



iOS8のUILocalNotificationに関して修正 - PartyIX