ukSeung iOS

[iOS] Background, Inactive(Foreground) 진입시 화면가리기 본문

iOS/Swift

[iOS] Background, Inactive(Foreground) 진입시 화면가리기

욱승 2023. 3. 23. 17:15

 

 

안녕하세요 욱승입니다.

해당 주제 관련은 보통 금융앱에서 많이 쓰이는데요

Background 혹은 Inactive상태가 됐을때 앱이 이미지 혹은 가려질 문구나 화면으로 가려지는 상태를 말합니다.

앱 생명주기를 아직 모른다면 ..! AppDelegate, SceneDelegate를 먼저 숙지바랍니다!

 

 

[iOS 앱개발] iOS 앱의 상태변화에 따른 AppDelegate, SceneDelegate 메서드

안녕하세요 Pingu입니다.🐧 오늘은 iOS에서 앱의 생명주기에 따라 호출되는 AppDelegate 메서드들을 알아볼 계획입니다. iOS 13 이후부터는 SceneDelegate가 생겨나서 AppDelegate가 하는 일들을 대체하는 메

icksw.tistory.com

해당 게시글은 iOS13이상 기준으로 작성되었습니다.

 

 


 

 

KBPay가 예시로 잘되있어 화면캡쳐 해봤다.

 

구현

//
//  SceneDelegate.swift
//  SceneDelegateExample
//
//  Created by plsystems on 2023/03/23.
//

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    var window: UIWindow?
    
    lazy var TAG_BG_IMG = -101
    lazy var bgLabel: UILabel = {
        let label = UILabel()
        label.frame = UIScreen.main.bounds
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 30)
        label.textColor = .white
        label.numberOfLines = 0
        label.text = "민감한 정보 숨기기"
        return label
    }()
    
    lazy var bgView: UIView = {
        let bgView = UIView()
        bgView.frame = UIScreen.main.bounds
        bgView.tag = TAG_BG_IMG
        bgView.backgroundColor = .black
        return bgView
    }()
    
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
    }
    
    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }
    
    // MARK: - 앱이 Active 상태가 되었을 때 호출되는 메서드입니다.
    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
        callBackgroundImage(false)
    }
    
    // MARK: - Active -> In-Active 상태로 변한 것을 알 수 있습니다.
    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
        callBackgroundImage(true)
    }
    
    // MARK: - 앱이 Foreground 상태가 됐을 때 호출되는 메서드입니다. (Background -> Foreground)
    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
        callBackgroundImage(false)
    }
    
    // MARK: - 앱이 Background 상태가 됐을 때 호출되는 메서드입니다. (Foreground -> Background)
    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
        callBackgroundImage(true)
    }
    
    /// 화면을 가리고 없애는 함수
    func callBackgroundImage(_ bShow: Bool) {
        
        let backgroundView = window?.rootViewController?.view.window?.viewWithTag(TAG_BG_IMG)
        
        if bShow {
            
            if backgroundView == nil {
                bgView.addSubview(bgLabel)
                window?.rootViewController?.view.window?.addSubview(bgView)
            }
        } else {
            
            if let backgroundView = backgroundView {
                backgroundView.removeFromSuperview()
            }
        }
    }
}

 

 

결과

 

 

결론

이런식의 결과 구현은 내가 해볼지는 잘 모르겠다. 개인정보에 민감한 어플리케이션일수록 이런식으로 많이 하는 것 같은데..

만약 하게된다면 쉽게 할 수 있을듯!

그리고 SceneDelegate 앱 생명주기에 대해서 다시한번 상기하게 되는 계기가 됐당

 

SceneDelegate, Yes I Can,,

728x90
반응형