[iOS] Notification

·2024년 1월 23일

알림은 앱 재사용률 높이는 효과가 있다.

local vs Remote

local

  • 앱 내에서 전달
  • 같은 시각 & 비슷한 컨텐츠
  • ex. 일기, 디데이, 할일

Remote

  • 서버에서 알림을 전달
  • 디른 시각 & 다양한 컨텐츠
  • ex. 광고, 채팅


알림 권한 설정하기

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)
    }
    
}
  1. Timeinterval 60s 이상이어야 반복 가능
  2. Identifier는 64개로 제한되어 있다
  3. 알림센터에 보이고 있는 지, 사용자에게 전달되었는 지 알 수 없다. 단, 사용자가 알림을 클릭하면 확인 가능하다.
  4. Foreground에서는 알림이 뜨지 않는 것이 default
    • forground에서 알림을 받고 싶다면, AppDelegate에서 Delegate를 채택(아래 참고)
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()
    }
}

0개의 댓글