티스토리 뷰

앱에서 알림을 처리하는 기능을 알아보겠습니다.

 

알림은 앱에서 알림을 생성하고 스케줄러를 통해 알림을 보내는 Local Notification 방식과 서버 알림 방식이 있는데, 여기서는 Local Notification 방식을 알아보겠습니다.

 

기존에 로컬 알림을 처리하는 객체는 UILocalNotification이었는데, iOS 10부터 사용자 알림에 관한 모든 것을 전담 처리하는  UserNotification 프레임워크를 제공하고 있습니다.

 

UserNotification은 UN 접두어를 사용하여 객체 이름을 정의하며 UserNotification 프레임워크에서 로컬 알림과 서버 알림의 차이는 단순히 구분값에 지나지 않아 통합적으로 구현이 가능하다는 장점이 있습니다.

 

알림 객체를 사용하기 위해 파일 상단에 반입 구문을 추가해야 합니다.

 

import UserNotifications

 

알림 기능을 사용하기 위한 주요 객체는 다음과 같습니다.

 

  • UNMutableNotificationContent : 알림 콘텐츠 (알림 타이틀, 서브 타이틀 및 알림 메시지 설정, 앱 아이콘 배지나 사운드 설정 등)
  • UNTimeIntervalNotificationTrigger : 알림 발송 조건 (알림 발생 시각과 반복 여부 설정)
  • UNNotificationRequest : 알림 요청 (알림 콘텐츠와 알림 발송 조건 객체를 모아 알림 요청 객체 생성)
  • UNUserNotificationCenter : 알림 발송 담당 (알림 객체가 등록되면 실제 발송 담당)

지금부터 실제 알림 기능을 구현해보겠습니다.

 

1.

AppDelegate.swift 파일에 UserNotification 프레임워크 임포트합니다.

 

import UserNotifications

 

2.

application(_:didFinishLaunchingWithOptions:) 메소드에 아래와 같은 코드를 추가하여 앱을 처음 실행할 때 알림 환경을 설정하고 사용자 동의를 받도록 구현합니다.

 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    if #available(iOS 11.0 , *) {
        // 경고창, 배지, 사운드를 사용하는 알림 환경 정보를 생성하고, 사용자 동의 여부 창을 실행
        let notiCenter = UNUserNotificationCenter.current()
        notiCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (didAllow, e) in }
    } else {
        // 경고창, 배지, 사운드를 사용하는 알림 환경 정보를 생성하고, 이를 애플리케이션에 저장
        let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(setting)
    }
    return true
}

 

3.

applicationWillResignActive(_ application: UIApplication) 메소드에 아래와 같은 코드를 추가하여 알림 콘텐츠 객체, 알림 발생 조건 객체, 알림 요청 객체 생성 후 NotificationCenter에 생성한 알림 요청 객체를 추가합니다.

 

// 앱이 비활성화 상태가 되었을 때 실행
func applicationWillResignActive(_ application: UIApplication) {
    if #available(iOS 10.0, *) {  // UserNotification 프레임워크를 이용한 로컬 알림 (iOS 10 이상)
        // 알림 동의 여부를 확인
        UNUserNotificationCenter.current().getNotificationSettings { settings in
        if settings.authorizationStatus == .authorized {
                // 알림 콘텐츠 객체
                let nContent = UNMutableNotificationContent()
                nContent.badge = 1
                nContent.title = "로컬 알림 메시지"
                nContent.subtitle = "준비된 내용이 아주 많아요! 얼른 다시 앱을 열어주세요!!"
                nContent.body = "앗! 왜 나갔어요??? 어서 들어오세요!!"
                nContent.sound = .default
                nContent.userInfo = ["name": "홍길동"]
                    
                // 알림 발생 조건 객체
                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
                    
                // 알림 요청 객체
                let request = UNNotificationRequest(identifier: "wakeup", content: nContent, trigger: trigger)
                    
                // 노티피케이션 센터에 추가
                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            } else {
                print("사용자가 알림을 동의하지 않음!!!")
            }
        }
    }
}

 

4.

앱을 실행한 후 홈 화면으로 빠져나가면 5초 뒤 아래와 같이 알림이 오는 것을 확인할 수 있습니다.

 

 

5.

전달 받은 알림을 처리하기 위해 UNUserNotificationCenterDelegate 프로토콜을 추가하고 노티피케이션 센터에 delegate 지정합니다.

 

import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if #available(iOS 11.0 , *) {
            ...
            notiCenter.delegate = self  // 알림 클릭 시 이벤트를 전달받을 객체로 self 지정
        } else {
            ...
        }
        return true
    }
    
    ...
}

 

6.

앱 실행 도중 알림이 오는 경우 아래 메소드가 실행되기 때문에 처리할 내용을 구현하면 됩니다.

 

// 앱 실행 도중에 알림 메시지가 도착한 경우
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    if notification.request.identifier == "wakeup" {
        let userInfo = notification.request.content.userInfo
        print(userInfo["name"]!)
    }
        
    // 알림 배너 띄워주기
    completionHandler([.alert, .badge, .sound])
}

 

7.

사용자가 알림 메시지를 클릭하는 경우 아래 메소드가 실행되므로 처리할 내용을 구현합니다.

 

// 사용자가 알림 메시지를 클릭했을 경우
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    if response.notification.request.identifier == "wakeup" {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo["name"]!)
    }

    completionHandler()
}

 


 

UserNotification 프레임워크를 사용하는 경우는 위와 같으며 그 이전 버전을 사용하는 경우는 깃허브 코드를 참고하시기 바랍니다.

 

또한, 현재는 앱을 종료 후 몇 초 후에 알림을 띄우도록 설정하였지만 특정 시간을 지정하여 알림을 띄울 수 있도록 할 수도 있습니다.

이 방식도 깃허브 코드를 통해 확인하시기 바랍니다.

 

https://github.com/hanbee1005/Msg-Notification

 

hanbee1005/Msg-Notification

iOS Local Notification Sample. Contribute to hanbee1005/Msg-Notification development by creating an account on GitHub.

github.com

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함