투덜이 개발자

swift 앱 종료 하기 예제 본문

Program Language/Swift

swift 앱 종료 하기 예제

엠투 2021. 5. 28. 14:39
반응형

실행중인 앱을 종료하고 싶을때가 이벤트 처리

 

import UIKit

class ViewController: UIViewController {

    
    @IBAction func btnClick(_ sender: Any) {
        
        let alert = UIAlertController(title: "앱종료하시겠습니까?", message : "저장하지 않은 내용은 삭제 될 수 있습니다.", preferredStyle: .alert)
        
        alert.addAction(UIAlertAction(title: "예", style: .default, handler: { action in
            
            self.showToast(message: "앱종료 실행") // 토스트 메세지 출력
            
            UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)

            
        }))
        alert.addAction(UIAlertAction(title: "아니오", style: .default, handler: nil))
        
        self.present(alert, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


    
    
}

extension UIViewController {
    
    func showToast(message : String) {
        
        let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
        toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        toastLabel.textColor = UIColor.white
        toastLabel.textAlignment = .center;
        toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
        toastLabel.text = message
        toastLabel.alpha = 1.0
        toastLabel.layer.cornerRadius = 10;
        toastLabel.clipsToBounds  =  true
        self.view.addSubview(toastLabel)
        UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
            toastLabel.alpha = 0.0
        }, completion: {(isCompleted) in
            toastLabel.removeFromSuperview()
        })
    } }
반응형