ios는 앱의 실행 상태에 따라 foreground (앱이 현재 보여지고 있을 때 ), background (앱이 백그라운드로 갔을 때)의 상태로 나누어진다.


background에서 앱이 실행되고 있을 때 Appdelegate.swift 파일에 있는 다양한 매소드를 통해서 상태에 따른 프로세스를 정의 할 수 있는데,

이번에는 로컬 알림을 설정하고 (사용자로부터 알림에 대한 동의를 받고) applicationDidEndterBackground 메소드를 통해 앱이 백그라운드로 돌아갔을때 알림을 주는 예제를 만들어 본다.





ViewController.swift 에 있는 viewDidLoad 메서드에 아래 코드를 입력한다.


override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        let app = UIApplication.sharedApplication()

        let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)

        app.registerUserNotificationSettings(notificationSettings)

        

 }





AppDelegate.swift 파일의 applicationDidEnterBackground 메서드에 아래 코드를 입력한다.


func applicationDidEnterBackground(application: UIApplication) {

        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        let app = UIApplication.sharedApplication()

        let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)

        app.registerUserNotificationSettings(notificationSettings)

        let alertTime = NSDate().dateByAddingTimeInterval(10) // 인터벌 10초 앱 백그라운드 진입 10초후로 세팅

        let notifyAlarm = UILocalNotification()

        

        notifyAlarm.fireDate = alertTime

        notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()

        notifyAlarm.soundName = "bell_tree.mp3"    //사전 넣어준 사운드 파일

        notifyAlarm.alertBody = "important metting in 30 minutes" // 알림 메시지

        app.scheduleLocalNotification(notifyAlarm)

}





위의 
코드는  "핵심만 골라 배우는 ios 9 프로그래밍 (닐스미스 지음/ 황반석 옮김)" 에 있는 예제를 참고하여 작성하였습니다.

+ Recent posts