iOS/코드조각

[iOS, Swift] LocalNotification 실행하기

검은참깨두유vm 2022. 8. 21. 09:05
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

import UserNotifications

class ViewController: UIViewController {

	lazy var button: UIButton = {
        var button = UIButton(type: .custom)
        button.setTitle("알림", for: .normal)
        return button
    }()

	override viewDidLoad() {
    	// Notification 알림 허용
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { didAllow, Error in
            print(didAllow)
        }
        
        view.addSubview(button)
        button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
    }
    
    @objc func didTapButton() {
	    // Notification에서 띄워줄 Content
        let content = UNMutableNotificationContent() 
        content.title = "Noti 연습"
        content.subtitle = "tistory"
        content.body = "lorem ipsum ...."
        content.badge = 1
        
        // Notification 실행 Trigger
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        
        // Notification Content와 Trigger를 NotificationCenter에 보내주는 역할을 함
        let request = UNNotificationRequest(identifier: "timerdone", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

}

 

실행 스크린샷 : 

반응형