Swift Notification in MacOS

kyle Kim·2022년 8월 16일
0

MacOS

목록 보기
1/1

MacOS로 개발하던 중 오른쪽 상단에 notification을 줘야할 경우가 생겼다. iOS와 비슷하게 만들면 된다.
1. 우선 User가 notification을 받을건지 허락을 받아야한다. 나 같은 경우에는 view를 init할때 호출하도록 만들었다.

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("NOTIFICATION SET")
            } else {
                print("NOTIFICATION FAILED")
            }
        }
  1. 이제 notification에 뭘 보여줄지 정해주면 된다. 크게 title, subtitle, 그리고 sound가 있다.
func notify() {
	let content = UNMutableNotificationContent()
	content.title = "TITLE HERE"
	content.subtitle = "Check it out"
	content.sound = UNNotificationSound.default
	let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false
	let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
	UNUserNotificationCenter.current().add(request)
}
  1. 마지막으로 notify function을 호출할 곳에 넣어주면 끝!! (SwiftUI로 작업했음)
Button(action: {
	self.notify()
}){
	Text("NOTIFY")
}

생각보다 iOS 개발할때와 차이가 많이 없어서 적용하기가 쉬웠다.

profile
가고일(gagoil)의 개발일지

0개의 댓글