Language/iOS,AOS

iOS Swift Notification 권한 확인하는 방법

건담아빠 2024. 7. 10. 16:50

iOS 단말기에서 알림설정 정보를 가져와서 표시해주자.

 

JavaScript

common.js

class Common {
  ...
  
  static isNotificationAuthorization() {
    if (Util.Browser.isAndroidApp()) {
    } else if (Util.Browser.isIosApp()) {
      window.isNotificationAuthorization = (jsonData) => {
        console.log('jsonData : ', jsonData);
        if (jsonData['isAllowedNotification'] === true) {
          console.log('AUTH OK');
        } else {
          console.log('AUTH NO');
        }
      };

      const message = {
        action: 'isNotificationAuthorization',
        callback: 'window.isNotificationAuthorization',
      };
      window.webkit.messageHandlers.IosBridge1.postMessage(message);
    }
  }
  
  ...
}

export default Common;

 

호출

Common.isNotificationAuthorization();


Swift (네이티브)

MainViewController

// MARK: - iOS Bridge
// 웹 액션 정의 : WebAction을 구분하는데 사용되는 타입
enum WebAction: String {
    ...
    case isNotificationAuthorization
    ...
}
extension MainViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard message.name == IOS_BRIDGE_NAME,
              let messageBody = message.body as? [String: Any],
              let action = messageBody["action"] as? String else { return }
        
        let webAction = WebAction(rawValue: action)
        
        Utils.Log("@@@@@@@@@@@@@@@@@@@@@@@ \(action)")
        
        switch webAction {
        
        ...
        
        case .isNotificationAuthorization:
            // 콜백 함수 실행
            guard let callback = messageBody["callback"] as? String else { return }

            Utils.isNotificationAuthorization(completion: { result in
                if result {
//                    Utils.Log("권한이 있습니다.")
                    let jsonData: [String: Any] = [
                        "isAllowedNotification": true
                    ]
                    
                    if let jsonString = Utils.convertDictionaryToJSONString(dictionary: jsonData) {
                        self.executeJavasScript(wKWeb: self.getActiveWkWebView(), callback: "\(callback)(\(jsonString));")
                    }
                } else {
//                    Utils.Log("권한이 없습니다.")
                    let jsonData: [String: Any] = [
                        "isAllowedNotification": false
                    ]
                    
                    if let jsonString = Utils.convertDictionaryToJSONString(dictionary: jsonData) {
                        self.executeJavasScript(wKWeb: self.getActiveWkWebView(), callback: "\(callback)(\(jsonString));")
                    }
                }
            })
            
        ....
    }
}

 

Utils

import Foundation
import UIKit
import WebKit
import UserNotifications

class Utils: NSObject {
    ...
    
    // 알림 권한 상태를 확인하는 함수
    static func checkNotificationAuthorizationStatus(completion: @escaping (UNAuthorizationStatus) -> Void) {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            DispatchQueue.main.async {
                completion(settings.authorizationStatus)
            }
        }
    }
    
    static func isNotificationAuthorization(completion: @escaping (Bool) -> Void) {
        checkNotificationAuthorizationStatus { status in
            switch status {
            case .authorized:
                Utils.Log("알림 권한이 허용되었습니다.")
                completion(true)
            case .denied:
                Utils.Log("알림 권한이 거부되었습니다.")
                completion(false)
            case .notDetermined:
                Utils.Log("아직 알림 권한을 설정하지 않았습니다.")
                completion(false)
            case .provisional:
                Utils.Log("알림 권한이 임시로 허용되었습니다.")
                completion(false)
            case .ephemeral:
                Utils.Log("임시 알림 권한이 허용되었습니다.")
                completion(false)
            @unknown default:
                Utils.Log("Unknown case")
                completion(false)
            }
        }
    }
}

 

iOS 단말기

설정 > 알림 > 알림 허용을 변경하면서 테스트 진행