iOS 개발 기록

[iOS] 로컬 푸쉬 - Local Notification 본문

iOS

[iOS] 로컬 푸쉬 - Local Notification

택꽁이 2022. 9. 7. 19:34
728x90

[개요]

 

Notification은 현재 네이티브 앱이 구현할 수 있는 매우 강력한 기능이다.

웹 앱의 큰 단점이 Notification을 상용할 수 없는 것이라 들었고, WWDC 2022에서 애플은 웹 앱에서도 Notification을 상용할 수 있도록 개선하겠다 발표했다. 그만큼 핵심적인 기능이라는 소리가 아닐까?  

 

방심하는 순간 엄청나게 쌓이는 푸쉬들 ...

 

Notification은 크게 두 종류가 있다.  

 - 로컬 푸쉬 : 앱으로부터 push를 앱에 띄우는 것.

 - 서버 푸쉬 : 서버로부터 push를 앱에 띄우는 것.


이 글은 Local Push에 관한 글이다.

 

 

 

[권한 요청]

 

Notification이 강력한 이유는 앱이 실행되지 않거나 백그라운드 상태에 있을 때에도 관련 정보를 전달할 수 있기 때문이다.  

애플은 이 기능이 사용자와의 작용에 있어 상호파괴적일 수 있다고 판단하여 관련 권한을 중요하게 생각하며, 이를 철저하게 관리한다. 

 

 

// 푸쉬를 다룰
let userNotiCenter = UNUserNotificationCenter.current()
// 사용자 알림 권한 요청
func requestNotiAuth() {
/// 요청하는 권한의 옵션
/// Document - https://developer.apple.com/documentation/usernotifications/unauthorizationoptions
let authOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)
/// 권한 요청
/// Document - https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649527-requestauthorization
userNotiCenter.requestAuthorization(options: authOptions) { success, error in
print(error)
}
}

 

 

 

 

[보내는 알림 내용 설정]

 

func sendNoti(seconds: Double) {
/// content 객체 생성 및 내용 설정
/// Document - https://developer.apple.com/documentation/usernotifications/unmutablenotificationcontent
let notiContent = UNMutableNotificationContent()
notiContent.title = "알림 Title"
notiContent.body = "알림 Body"
/// trigger - Notification을 언제 보낼지에 대한 설정
/// Document - https://developer.apple.com/documentation/usernotifications/unnotificationtrigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: seconds, repeats: false)
/// request
let request = UNNotificationRequest(identifier: "TestNoti", content: notiContent, trigger: trigger)
userNotiCenter.add(request) { error in
if let error = error {
print(error)
}
}
}
view raw sendNoti.swift hosted with ❤ by GitHub

 

 

 

[Notification의 Delegate 설정]
AppDelegate에 구현해야 한다. 

 

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
/// 여기에 추가한다!
UNUserNotificationCenter.current().delegate = self
return true
}
/// AppDelegate의 기타 메서드들...
}
/// UNUserNotificationCenterDelegate 상속
/// Document - https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
/// notification 을 통해 앱을 실행시킬 경우
/// Document - https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649501-usernotificationcenter
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
print("didReceived!")
}
/// 앱이 forground일 때에도 Notification을 받을수 있도록 하는 메서드
/// Document - https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.list, .badge, .sound])
}
}

 

 

 

[결과] 

 

잘 보내지는 것을 확인할 수 있다! 

 

[참고]

 

https://developer.apple.com/documentation/usernotifications/scheduling_a_notification_locally_from_your_app

 

Apple Developer Documentation

 

developer.apple.com