본문 바로가기

아이폰

SWIFTUI FCM , PHP 전송

반응형

1. 애플 개발자 등록

 

1)애플 개발자 사이트:  https://developer.apple.com/ 

2)애플은 개발자 등록비 1년 129,000원입니다. 1년마다 등록비 갱신해주셔야 합니다. 

3)2-3일 정도 걸립니다. 

 

2. 키등록 

https://developer.apple.com/account/resources/authkeys/list 이동

1) +버튼 눌러서 키 등록 (Apple Push Notifications service (APNs) 체크)

2) APN 인증 파일 다운로드 (.p8 확장자 ) , Key ID는 메모 해놓을 것!

 

3. App ID 등록 

https://developer.apple.com/account/resources/identifiers/list 이동

1)+버튼 눌러서  App IDs 선택 후 다음

2)Description,  Bundle ID  입력 , push notification 체크 , Team ID 메모 해놓을것!

 

 

4. Firebase

1) https://console.firebase.google.com/?hl=ko 이동

2) 프로젝트 생성

3) 앱등록 : 번들아이디 입력 -> GoogleService-Info.plist 파일 다운 -> 완료

4) 프로젝트 설정 이동 -> 클라우드 메시징 탭 이동

5) APN인증키  등록  : 2-2에서 다운 받은 p8파일

6)  Key ID, Team ID  등록

 

5.XCode 설정

1) 프로젝트에 GoogleService-Info.plist 파일 복사

2) Project->TARGETS -> sign&capabilities 탭 -> +capabilities 버튼클릭

    BackGround mode 추가 (Background fetch , Remote notifications 선택)

    Push Notifications 추가 

 

3)  File -> Swift Pakages ->  Add Package dependency 

    https://github.com/firebase/firebase-ios-sdk.git 입력

    FirebaseMessaging 체크 후 Add Package

 

4) 코드

 

FcmTestApp.swift

import SwiftUI

@main
struct FcmTestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

 

 

AppDelegate.swift

import SwiftUI
import UserNotifications


import FirebaseCore
import FirebaseMessaging


class AppDelegate: NSObject, UIApplicationDelegate {
    
    private var gcmMessageIDKey = "gcm_message_idKey"
    static var fcmToken = String()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self
        registerForPushNotifications()
        
        return true
    }
    
    func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
            print("Permission granted: \(granted)")
            guard granted else { return }
            self?.getNotificationSettings()
        }
    }
    
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    
    func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
       
        AppDelegate.fcmToken = deviceToken.hexString
    }
    
    func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        print("Failed to register: \(error.localizedDescription)")
    }
    
    func application(
        _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       
        print(userInfo)
        completionHandler(.newData)
    }
}


@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        let userInfo = notification.request.content.userInfo
        print("Will Present User Info: \(userInfo)")
        
        completionHandler([[.banner, .sound]])
    }
    
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void) {
        
        let userInfo = response.notification.request.content.userInfo
        
        if response.actionIdentifier == "accept" {
            print("Did Receive User Info: \(userInfo)")
            
            completionHandler()
        }
    }
}


extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        let dataDict: [String: String] = [AppDelegate.fcmToken: fcmToken ?? ""]
        NotificationCenter.default.post(name: NSNotification.Name("FCMToken"), object: nil, userInfo: dataDict)


        // Note: This callback is fired at each app startup and whenever a new token is generated.
        AppDelegate.fcmToken = fcmToken!
        
        print("device token  , \(fcmToken!)")
        //서버로 푸시토큰 전송
    }
}


extension Data {
    var hexString: String {
        let hexString = map { String(format: "%02.2hhx", $0) }.joined()
        return hexString
    }
}

 

5. 서버에서 푸시 발송(php)

 


$server_key = "AAAAD2tpLsU:APA91bGWFSHq8JkpnhugEI5g-byLYxOPkP3lxXK7PxsapZZlvDtaEsBkGsHgmgLs9dvtnUqfHz5WOJMOkbHQaMB6v5qC6BLLkCMVtnai8dCIgxxxxxxx";
$url = "https://xxxx.cafe24.com/web";
$device_id =   '폰으로 부터 받은 디바이스 토큰';
$push_result = sendNotification("댓글 등록알림", "댓글이 등록되었습니다.", ["url" => $url], $device_id , $server_key);


function sendNotification($title = "", $body = "", $customData = [], $to = "", $serverKey = ""){
    if($serverKey != ""){
        ini_set("allow_url_fopen", "On");
        $data =
        [
            "to" => $to,
            "notification" => [
                "body" => $body,
                "title" => $title,
            ],
            "data" => $customData
        ];

        $options = array(
            'http' => array(
                'method'  => 'POST',
                'content' => json_encode( $data ),
                'header'=>  "Content-Type: application/json\r\n" .
                            "Accept: application/json\r\n" .
                            "Authorization:key=".$serverKey
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
        return json_decode( $result );
    }
    return '0';
}
반응형