[Swift] 어플이 중단될 때, 어플이 다시 실행될 때 감지하는 법

프로그래밍/iOS 관련2017. 11. 23. 19:34

안녕하세요. 개발자 드리머즈입니다.


어플 실행 도중에 홈 버튼을 눌러, 중단되거나,

홈 화면에서 다시 어플 아이콘을 눌러 중단된 어플이 실행될 때를

어떻게 감지(detect)하는지가 궁금했습니다.


찾아보니..AppDelegate.swift파일에서 쉽게 감지 가능합니다.

AppDelegate에는 아래와 같은 함수들이 기본적으로 존재합니다.


print()함수를 이용해 이 함수가 언제 불리는지 확인해봤습니다.

func applicationWillResignActive(_ application: UIApplication) {
        print("applicationWillResignActive")
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        print("applicationDidEnterBackground")
        // 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.
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        print("applicationWillEnterForeground")
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        print("applicationDidBecomeActive")
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        KOSession.handleDidBecomeActive()
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        print("applicationWillTerminate")
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


App 실행 도중에 홈 버튼을 눌러 홈 화면으로 나간 경우

applicationWillResignActive

applicationDidEnterBackground


홈 화면에서 다시 App 아이콘을 눌러 App을 실행시킨 경우

applicationWillEnterForeground

applicationDidBecomeActive



Xcode debug console에서 로그 확인 결과 위와 같았습니다.

따라서 위의 함수들을 잘 이용하면 어플이 중단될 때와 다시 실행될 때를 알 수 있습니다.






작성자

Posted by 드리머즈

관련 글

댓글 영역