source

Firebase Cloud Messaging에서 푸시 알림을 생성하지 않고 정보를 가져옵니다.

ittop 2023. 7. 6. 22:34
반응형

Firebase Cloud Messaging에서 푸시 알림을 생성하지 않고 정보를 가져옵니다.

저는 iOS 앱에 푸시 알림을 넣으려고 이 튜토리얼(https://www.youtube.com/watch?v=JsWHzU1DxjM) 을 통해 작업하고 있었습니다.APNS에 대한 인증서를 성공적으로 취득하고 "push notification" 및 "background modes" 기능을 on으로 설정할 수 있었습니다.또한 Firebase는 Firebase 콘솔에서 알림을 보낼 때 알림에서 정보를 얻을 수 있습니다.그러나 앱이 백그라운드에서 실행될 때 배너 알림이 나타나지 않습니다.튜토리얼이 Objective-C에 있었기 때문에 튜토리얼을 Objective-C에서 Swift로 변환하는 데 문제가 있었던 것 같은데 잘 모르겠습니다.도움이 된다면 앱 대표 수업과 프로그램 출력을 넣었습니다.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    connectToFcm()

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: #selector(tokenRefreshCallback),
        name: kFIRInstanceIDTokenRefreshNotification,
        object: nil)

    let allNotificationTypes = UIUserNotificationType(arrayLiteral: UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge)
    let settings = UIUserNotificationSettings(forTypes: allNotificationTypes, categories: nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}

override init() {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = false
}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    connectToFcm()
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    //try! FIRAuth.auth()!.signOut()
}

func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
        if (error != nil) {
            print("Unable to connect with FCM. \(error)")
        } else {
            print("Connected to FCM.")
        }
    }
}


func tokenRefreshCallback(notification: NSNotification) {
    let refreshedToken = FIRInstanceID.instanceID().token()
    print("InstanceID token: \(refreshedToken)")

    // Connect to FCM since connection may have failed when attempted before having a token.
    if (refreshedToken != nil)
    {
        connectToFcm()
    }

    }

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("\(userInfo)")
    //print("Message ID: \(userInfo["gcm.message_id"]!)")
    NSNotificationCenter.defaultCenter().postNotificationName("name", object: userInfo)

    // Print full message.
    print("%@", userInfo)
}
}

콘솔 로그:

2016-06-20 19:14:50.801 MapKitTry[2244:721460] Configuring the default app.
2016-06-20 19:14:50.839 MapKitTry[2244:] <FIRAnalytics/INFO> Firebase Analytics v.3200000 started
2016-06-20 19:14:50.846 MapKitTry[2244:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see -omitted-)
2016-06-20 19:14:50.849: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-20 19:14:50.849: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-06-20 19:14:50.853: <FIRMessaging/INFO> FIRMessaging library version 1.1.0
2016-06-20 19:14:50.863: <FIRMessaging/WARNING> FIRMessaging AppDelegate proxy enabled, will swizzle app delegate remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-20 19:14:50.902 MapKitTry[2244:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
no login
2016-06-20 19:14:51.076 MapKitTry[2244:] <FIRAnalytics/INFO> Firebase Analytics enabled
Connected to FCM.
[notification: {
body = "Push notification";
e = 1;
}, collapse_key: pdrum3.KingOfTheTown, from: 302278087187]
%@ [notification: {
body = "Push notification";
e = 1;
}, collapse_key: pdrum3.KingOfTheTown, from: 302278087187]

더하다FirebaseAppDelegateProxyEnabledinfo.plist에 "Boolean" 값 "NO"를 입력합니다.

info.plist-image

나는 또한 이것을 나의 것에 추가해야 했습니다.AppDelegate여기서 충고한 바와 같이

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
}

알림을 받을 수 있는 UNUserNotificationDelegate 메서드가 없습니다.

extension NotificationManager: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {

        switch response.actionIdentifier {

        // NotificationActions is a custom String enum I've defined
        case NotificationActions.HighFive.rawValue:
            print("High Five Delivered!")
        default: break
        }
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {

        // Delivers a notification to an app running in the foreground.
    }
}

이 두 가지 대리인 방법은 현재 수신에 사용 중인 이전 대리인 방법(즉, 원격 통지 수신)을 대체합니다.자세한 내용은 이 튜토리얼을 참조하십시오. http://cleanswifter.com/ios-10-local-notifications/

info.plist 파일 내에 추가하고 소스 코드(info.plist 파일)로 엽니다.

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

언급URL : https://stackoverflow.com/questions/37933387/firebase-cloud-messaging-doesnt-create-push-notifications-but-gets-information

반응형