본문 바로가기

IOS Swift/Swift 공부 기록

IOS SWIFT: Notification Push 보내기(개발자 계정 X)

import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate{

public override func viewDidLoad() {
    super.viewDidLoad()
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge],
                                                            completionHandler: {didAllow,Error in
        print(didAllow) })
        
    UNUserNotificationCenter.current().delegate = self
    }
      
@IBAction func pushButton(_ sender: Any) {
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "푸시 제목"
    content.subtitle = "부제목"
    content.body = "푸시 내용"
    content.sound = UNNotificationSound.default
    content.categoryIdentifier = "chatting-message"
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
    let requeset = UNNotificationRequest(identifier: "chatting",
                                         content: content,
                                         trigger: trigger)
    center.add(requeset) { error in
    if let error = error { print("error : \(error)")}
    }
}

public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
                     withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       
    print("notificationcenter will Present \(notification)")
    completionHandler([.alert, .sound,.badge])
        
    }

public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
                     withCompletionHandler completionHandler: @escaping () -> Void) {
       
    print("notificationcenter did Present \(response)")
    completionHandler()
        
    }   
}       


왜 코드 블록이 가독성 있게 완성이 안 되는지는 모르지만 기록용으로 게시한 로컬 디바이스에 푸시 보내는 코드

델리게이트를 해야 백그라운드가 아닌 포그라운드에서도 푸쉬를 받는 게 가능하다

viewdidload()에 푸시 알림 접근 권한 설정 승인 안내를 띄우고 Allow시 푸시를 받을 수 있게 지정

컨텐트, 트리거, 리퀘스트가 필요하고 권한 부여 코드에 []에 넣은 설정들만 푸쉬 콘텐츠에 반영시킬 수 있으니 주의!

 

개인적으로 개인 개발자 계정을 구매해서 인증서라던가 APNs서버 전송이라던가 Firebase연동해서 하고 싶지만 

푸시 하나 하겠다고 거금을 들여 계륵 같은 계정을 두는 것보단 삽질에 삽질을 거듭해서 실시간 Observer 함수에 event감지를 넣어서

local 푸쉬를 받을 수 있게 응용하는 것도 나쁘진 않을 것 같다.

위의 코드를 응용해서 시뮬을 여러 개 띄워해 봐야지