seong_hye, the developer

Swift) Notification에 대해 알아보기 본문

IOS

Swift) Notification에 대해 알아보기

seong_hye 2022. 10. 19.

 

notification은 쉽게 말하면 앱에서 오는 알림이다

iOS에서는 크게 두 가지로 나뉘어 진다

- NotificationCenter : 앱 내부에서 메시지를 주고 받는 방법

- Push Notification : 외부 서버에서 사용자 기기로 보내는 알림

 

이 내용에 대해 자세히 알아보자


📘 NotificationCenter

앱 내부에서 이벤트를 전달하는 "게시 - 구독(Pub - Sub)" 방식의 메시지 시스템


🔹 사용 예시

✅ 알림 보내기 (Post)

NotificationCenter.default.post(name: .testNotification, object: nil)

 

✅ 알림 수신 (Add Observer)

NotificationCenter.default.addObserver(forName: .testNotification, object: nil, queue: .main) { _ in
	print("알림 받음")
}

 

✅ 사용자 정의 Notification 이름

extension Notification.Name {
	static let testNotification = Notification.Name("testNotification")
}

🔹 사용 목적

상황 예시
상태 변경 통보 로그인 성공, 로그아웃
시스템 이벤트 감지 키보드 표시 여부 등
화면 간 이벤트 전달 탭 전달, 데이터 변경 등

📘 PushNotification

서버 -> Apple Push Notification Server(APNs) -> 사용자 디바이스로 알림을 보내는 시스템

앱이 꺼져 있어도 받을 수 있음


🔹 동작 흐름

1. 앱 > APNs 등록 > device token 획득

2. 앱 > 서버로 token 전송

3. 서버 > APNs로 메시지 전송 (token 포함)

4. APNs > 사용자 디바이스에 푸시 표시


🔹iOS 연동 코드

 알림 권한 설정

import UserNotifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
	if granted {
    	DispatchQueue.main.async {
        	UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

 

 푸시 토큰 등록

func application(_ application: UIApplication,
				didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
	let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device Token: \(token)")
    
    // 서버에 토큰 전송
}

🔹 구성 요소

구성 역할
Device Token APNs에서 발급하는 고유 디바이스 식별자
APNs Apple의 푸시 알림 서버
Firebase / 자체 서버 알림을 생성하고 APNs에 전송
앱에서 푸시 권한 요청 사용자에게 알림 수신 허용 받기

🔹 푸시 알림 종류

🔍 Local Notification

앱 내부에서 직접 생성하여 디바이스에 표시되는 알림

ex) 사용자가 "알람시계"를 직접 설정해놓고 울리는 것 (앱이 스스로 만든 알림)

 

➡️ 예시 코드

import UserNotifications


func scheduleLocalNotification() {
	let content = UNMutableNotificationContent()
    content.title = "알림"
    content.body = "로컬 알림입니다"
    contnet.sound = .default
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    
    UNNotificationCenter.current().add(request)
}

 + 앱에 권한 요청 해야 함

 

⚠️ Local Notification은 내부에서 진행되기에 Push Notification 이라고 할 수 없음

하지만 시스템 알림이기에 Push Notification의 한 종류임


🔍 Remote Notification

Push Notification 자체라고 볼 수 있음

ex) 누군가 서버에서 사용자에게 메시지를 "보내줌" (iOS가 받아서 띄워줌)

 

 Local Notification vs Remote Notification

항목  Local Notification Remote Notification
생성 위치 앱 내부에서 직접 생성 외부 서버에서 생성 후 APNs에 전송
네트워크 필요 X O
사용 목적 알람, 타이머, 캘린더 등 메시지, 마케팅, 긴급 알림 등
앱 꺼져 있을 때 수신 가능 (예약된 로컬 알림) 가능
설정 난이도  낮음 중간 ~ 높음 (토큰, 서버 필요)
사용자 권한 필요 필요함 필요함
예시 "10분 뒤 알람", "일일 체크인" "새로운 메시지가 도착했습니다", "이벤트 안내"

🔹 NotificationCenter  vs  Push Notification 비교

구분 NotificationCenter Push Notification
사용 범위 앱 내부 외부 서버 -> 디바이스
인터넷 필요 X O
앱 종료 시 수신 X O
예시 화면 간 데이터 전달 메시지, 경고, 마케팅 등
구현 난이도  쉬움 중간 ~ 높음

 

📌 Local Notification과 NotificationCenter는 어떻게 다를까?

둘은 완전히 다른 개념

항목 Local Notification Notification Center
사용자에게 알림 표시 O X
iOS 알림 센터 표시 O X
앱 꺼져 있을 때 동작 O X
API 클래스 UNUserNotificationCenter NotificationCenter
용도 사용자에게 알림 전달 앱 내부에서 객체 간 메시지 전달
예시 "10분 뒤 알림 띄우기" "로그인 완료되면 다른 뷰도 갱신하기"

 


 

Comments