알림은 앱 재사용률 높이는 효과가 있다.
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 알림 권한 설정
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { success, error in
print(success, error)
}
return true
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func localNotiBtnClicked(_ sender: UIButton) {
// 1. 컨텐츠
let content = UNMutableNotificationContent()
content.title = "장바구니 확인해보셨나요?"
content.body = "찜한 상품을 구매해보세요"
content.badge = 100
// 2. 언제
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) // 몇 초 뒤에 보낼건지, 반복 할건지
// 2.1. 캘린더 기반
var component = DateComponents()
component.hour = 10
component.minute = 25
let calendarTrigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
// 3. 요청
let request = UNNotificationRequest(identifier: "\(Date())", content: content, trigger: calendarTrigger)
// 3. 요청
let request = UNNotificationRequest(identifier: "\(Date())", content: content, trigger: trigger)
// 4. iOS system에 등록
UNUserNotificationCenter.current().add(request)
}
}
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// foreground에서 알림을 받고자 할 경우
// ex. 1:1 채팅할 경우, 채팅방마다 푸시 설정이 다르므로 특정 화면/특정 조건에 대해서 포그라운드 알림을 받게 설정하는 것도 가능
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .badge, .list, .sound])
}
}
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow? // nil => storyboard
func sceneDidBecomeActive(_ scene: UIScene) {
// 뱃지 제거
UIApplication.shared.applicationIconBadgeNumber = 0
// 사용자에게 이미 전달되어 있는 노티들을 제거
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
// 사용자에게 전달이 될 예정인 노티들을 제거
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}