새소식

iOS/Swift

[Swift] User Notifications

  • -

User Notifications

 

User Notifications | Apple Developer Documentation

Push user-facing notifications to the user’s device from a server, or generate them locally from your app.

developer.apple.com


- 사용자 기기에 대면으로 서버나 로컬에서 알림을 전송해 주는 Framework

 

 

 

UnUserNotificationCenter

 

UNUserNotificationCenter | Apple Developer Documentation

The central object for managing notification-related activities for your app or app extension.

developer.apple.com


-  App이나 App Extension에서 알림을 관리하거나 알림과 관련된 활동을 관리하는 중앙 객체

 

// AppDelegate.swift
import UserNotifications

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    // 알림 권한 요청
    UNUserNotificationCenter.current().delegate = self


    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {
        success, error in

        if(error != nil){
            print("권한 요청 실패 : \(error?.localizedDescription)")
        }
        else{
            print("권한 요청 성공")
        }
    })

    return true
}

extension AppDelegate: UNUserNotificationCenterDelegate{
    
    // Foreground상 에서 알림 요청
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
           completionHandler([.list, .banner])
       }
}

 

 

 

로컬에서 Push 알림 Request


func pushNotification(_ title: String, _ body: String){
        
        // Content 설정
        let notiContent = UNMutableNotificationContent()
        notiContent.title = title
        notiContent.body = body
        
        // 시간 (timeInterval 후에 알림 전송, 반복 여부)
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2.0, repeats: false)
        
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: notiContent, trigger: trigger)
        
        // 요청
        UNUserNotificationCenter.current().add(request){ error in
            
            if(error != nil){
                print("Push Failed : \(error?.localizedDescription)")
            }
            
        }
        
    }

 

 

출처

https://dokit.tistory.com/50
728x90

'iOS > Swift' 카테고리의 다른 글

[Swift] Dynamic Library vs Static Library  (0) 2023.08.21
[Swift] Core Data  (0) 2023.08.21
[Swift] @discardableResult  (0) 2023.07.26
[Swift] Date / DateFormatter  (0) 2023.07.15
[Swift] UserDefault  (0) 2023.07.15
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.