先日こんなお問い合わせをいただいた.
@h3_poteto ブログ見てツイートさせていただきました。
ローカル通知についてもっと教えて教えて欲しいです。
アプリが起動してない時にどこの部分の処理が行われるのかなど、
できれば、「iOS8でUILocalNotificationの通知を受け取る」のソースが見たいです。
— EVESANTA@きらしほし (@evesanta1224) February 22, 2015
というわけで,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