3

그래서, 문제는 푸시가 오는 내가이 메시지가 나타납니다 중포 기지를 사용하여 내 응용 프로그램에 푸시 알림을 구현하기 위해 노력하고있어 :중포 기지 푸시 알림 3

[AnyHashable ("id_entity을") : AnyHashable ("body") : alhoteable, AnyHashable ("from")에 의한 테스트 : 1054934643579, AnyHashable ("title") : 푸시 알림 테스트, AnyHashable ("subject") : offer]

하지만 아이폰에는 나오지 않습니다. 아무 것도 전경이 아니라 배경에 나타나지 않습니다. 어떤 도움이 필요합니까? ,

var window: UIWindow? 
let gcmMessageIDKey = "gcm.message_id" 
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    //UITabBar.appearance().tintColor = myGreenColor 
    UINavigationBar.appearance().barTintColor = myGreenColor 
    UINavigationBar.appearance().tintColor = UIColor.white 
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] 
    UIApplication.shared.statusBarStyle = .lightContent 
    //UP Screen when keyboard appear. 
    IQKeyboardManager.sharedManager().enable = true 
    // Override point for customization after application launch. 

    //MARK:-Push Notifications 
    if #available(iOS 10.0, *) { 
     let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound] 
     UNUserNotificationCenter.current().requestAuthorization(
      options: authOptions, 
      completionHandler: {_,_ in }) 

     // For iOS 10 display notification (sent via APNS) 
     UNUserNotificationCenter.current().delegate = self 
     // For iOS 10 data message (sent via FCM) 
     FIRMessaging.messaging().remoteMessageDelegate = self 
     //application.registerForRemoteNotifications() 
    } else { 
     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
     //application.registerForRemoteNotifications() 
    } 
    application.registerForRemoteNotifications() 

    // [END register_for_notifications] 
    FIRApp.configure() 

    // [START add_token_refresh_observer] 
    // Add observer for InstanceID token refresh callback. 
    NotificationCenter.default.addObserver(self, 
              selector: #selector(self.tokenRefreshNotification), 
              name: .firInstanceIDTokenRefresh, 
              object: nil) 
    // [END add_token_refresh_observer] 
    return true 
} 


// [START receive_message] 
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 
    // 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. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 
} 

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], 
       fetchCompletionHandler completionHandler: @escaping (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. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 

    completionHandler(UIBackgroundFetchResult.newData) 
} 
// [END receive_message] 

// [START refresh_token] 
func tokenRefreshNotification(_ notification: Notification) { 
    if let refreshedToken = FIRInstanceID.instanceID().token() { 
     Persistence.setMobileUuid(refreshedToken) 
     print("InstanceID token: \(refreshedToken)") 
    } 
    // Connect to FCM since connection may have failed when attempted before having a token. 
    connectToFcm() 
} 
// [END refresh_token] 





// [START connect_to_fcm] 
func connectToFcm() { 
    // Won't connect since there is no token 
    guard FIRInstanceID.instanceID().token() != nil else { 
     return 
    } 

    // Disconnect previous FCM connection if it exists. 
    FIRMessaging.messaging().disconnect() 

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



// [END connect_to_fcm] 
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
    print("Unable to register for remote notifications: \(error.localizedDescription)") 
} 


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 invalidate graphics rendering callbacks. 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. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
    FIRMessaging.messaging().disconnect() 
    print("Disconnected from FCM.") 

} 

func applicationWillEnterForeground(_ application: UIApplication) { 
    // 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. 
    connectToFcm() 
    refresh_Token() 
} 

func applicationWillTerminate(_ application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 

// Refresh User Token 
func refresh_Token(){ 
    if let rememberToken = Persistence.getRemember_token(), rememberToken != "" { 
     ApiManager().Remember_Me(remember_token: rememberToken){ (success) ->() in 
      if success { 
       print("Rifreskimi i token u be me sukses") 
      } 
     } 
    } 
} 



} 

// [START ios_10_message_handling] 
@available(iOS 10, *) 
extension AppDelegate : UNUserNotificationCenterDelegate { 

// Receive displayed notifications for iOS 10 devices. 
internal func userNotificationCenter(_ center: UNUserNotificationCenter, 
            willPresent notification: UNNotification, 
            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    let userInfo = notification.request.content.userInfo 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 

    // Change this to your preferred presentation option 
    completionHandler([]) 
} 

func userNotificationCenter(_ center: UNUserNotificationCenter, 
          didReceive response: UNNotificationResponse, 
          withCompletionHandler completionHandler: @escaping() -> Void) { 
    let userInfo = response.notification.request.content.userInfo 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 

    completionHandler() 
} 
} 
// [END ios_10_message_handling] 
// [START ios_10_data_message_handling] 
extension AppDelegate : FIRMessagingDelegate { 
// Receive data message on iOS 10 devices while app is in the foreground. 
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { 
    print(remoteMessage.appData) 
} 
} 
// [END ios_10_data_message_handling] 
+0

Welcome to StackOverflow! 질문을 관련 코드로 업데이트 해 주실 수 있습니까? –

+0

고맙습니다. 질문에 코드를 추가했습니다. – Stephanie

+0

은 푸시 알림이며 백엔드에서 보내고 firebase 콘솔에서는 보내지 않습니까? –

답변

1

이와 앱 대리자를 교체하려고 나를 위해 작동

내가 스위프트 4 코드를 구현
import UIKit 
import UserNotifications 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
    let gcmMessageIDKey = "gcm.message_id" 
    let spm = SharedPref() 

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

     // Register for remote notifications. This shows a permission dialog on first run, to 
     // show the dialog at a more appropriate time move this registration accordingly. 
     // [START register_for_notifications] 



     if #available(iOS 10.0, *) { 
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] 
      UNUserNotificationCenter.current().requestAuthorization(
       options: authOptions, 
       completionHandler: {_, _ in }) 

      // For iOS 10 display notification (sent via APNS) 
      UNUserNotificationCenter.current().delegate = self 
      // For iOS 10 data message (sent via FCM) 
      FIRMessaging.messaging().remoteMessageDelegate = self 

     } else { 
      let settings: UIUserNotificationSettings = 
       UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
      application.registerUserNotificationSettings(settings) 
     } 

     application.registerForRemoteNotifications() 

     // [END register_for_notifications] 
     FIRApp.configure() 

     // [START add_token_refresh_observer] 
     // Add observer for InstanceID token refresh callback. 
     NotificationCenter.default.addObserver(self, 
               selector: #selector(self.tokenRefreshNotification), 
               name: .firInstanceIDTokenRefresh, 
               object: nil) 
     // [END add_token_refresh_observer] 
     return true 
    } 

    // [START receive_message] 
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 
     // 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. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print("ccc\(userInfo)") 
    } 

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], 
        fetchCompletionHandler completionHandler: @escaping (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. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print("ddd\(userInfo)") 

     completionHandler(UIBackgroundFetchResult.newData) 
    } 
    // [END receive_message] 
    // [START refresh_token] 
    func tokenRefreshNotification(_ notification: Notification) { 
     if let refreshedToken = FIRInstanceID.instanceID().token() { 

      print("InstanceID token: \(refreshedToken)") 


      spm.setFcmToken(password: refreshedToken) 

     } 

     // Connect to FCM since connection may have failed when attempted before having a token. 
     connectToFcm() 
    } 
    // [END refresh_token] 
    // [START connect_to_fcm] 
    func connectToFcm() { 
     // Won't connect since there is no token 
     guard FIRInstanceID.instanceID().token() != nil else { 
      return; 
     } 

     // Disconnect previous FCM connection if it exists. 
     FIRMessaging.messaging().disconnect() 

     FIRMessaging.messaging().connect { (error) in 
      if error != nil { 
       print("Unable to connect with FCM. \(error)") 
      } else { 
       print("Connected to FCM.") 
      } 
     } 
    } 
    // [END connect_to_fcm] 
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
     print("Unable to register for remote notifications: \(error.localizedDescription)") 
    } 

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled. 
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to 
    // the InstanceID token. 
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
     print("APNs token retrieved: \(deviceToken)") 

     // With swizzling disabled you must set the APNs token here. 
     // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox) 
    } 

    // [START connect_on_active] 
    func applicationDidBecomeActive(_ application: UIApplication) { 
     connectToFcm() 
    } 
    // [END connect_on_active] 
    // [START disconnect_from_fcm] 
    func applicationDidEnterBackground(_ application: UIApplication) { 
     FIRMessaging.messaging().disconnect() 
     print("Disconnected from FCM.") 
    } 
    // [END disconnect_from_fcm] 
} 

// [START ios_10_message_handling] 
@available(iOS 10, *) 
extension AppDelegate : UNUserNotificationCenterDelegate { 

    // Receive displayed notifications for iOS 10 devices. 
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
           willPresent notification: UNNotification, 
           withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
     let userInfo = notification.request.content.userInfo 
     // Print message ID. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print("aaa\(userInfo)") 

     // Change this to your preferred presentation option 
     completionHandler([.alert, .badge, .sound]) 
    } 
    //when we click on notificaiton 
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
           didReceive response: UNNotificationResponse, 
           withCompletionHandler completionHandler: @escaping() -> Void) { 
     let userInfo = response.notification.request.content.userInfo 
     // Print message ID. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print("bbb\(userInfo)") 
     // 
     //Code to be executed when you click notification 

     // 
     completionHandler() 
    } 
} 
// [END ios_10_message_handling] 
// [START ios_10_data_message_handling] 
extension AppDelegate : FIRMessagingDelegate { 
    // Receive data message on iOS 10 devices while app is in the foreground. 
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { 
     print(remoteMessage.appData) 
    } 
} 
+0

이 경우에는 작동하지 않습니다. 시도했지만 아무것도하지 않았습니다. – Stephanie

0

: 아래

내가 사용했던 코드

* *

import UIKit 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 
import UserNotifications 

    @UIApplicationMain 
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate { 

var window: UIWindow? 
let gcmMessageIDKey = "gcm.message_id" 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 
    UINavigationBar.appearance().barTintColor = UIColor(red: 80.0/255.0, green: 151.0/255.0, blue: 199.0/255.0, alpha: 1.0) 
    UINavigationBar.appearance().tintColor = UIColor.white 
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white] 
    // Override point for customization after application launch. 
    //MARK:-Push Notifications 
    if #available(iOS 10.0, *) { 
     let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound] 
     UNUserNotificationCenter.current().requestAuthorization(
      options: authOptions, 
      completionHandler: {_,_ in }) 

     // For iOS 10 display notification (sent via APNS) 
     UNUserNotificationCenter.current().delegate = self 
     // For iOS 10 data message (sent via FCM) 
     Messaging.messaging().delegate = self 
     //application.registerForRemoteNotifications() 
    } else { 
     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
     //application.registerForRemoteNotifications() 
    } 
    application.registerForRemoteNotifications() 
    // [END register_for_notifications] 
    FirebaseApp.configure() 
    return true 
} 


@objc func tokenRefreshNotification(_ notification: Notification) { 
    if let refreshedToken = InstanceID.instanceID().token() { 
     print("InstanceID token: \(refreshedToken)") 
    } 
    // Connect to FCM since connection may have failed when attempted before having a token. 
    ConnectToFCM() 
} 
func ConnectToFCM() { 
    Messaging.messaging().shouldEstablishDirectChannel = true 
    if let token = InstanceID.instanceID().token() { 
     // print("#########################################") 
     print("DCS: " + token) 

     //MARK: Save Device Token in UserDefaults 
     UserDefaults.standard.set(token, forKey: "deviceToken") //setObject 
     UserDefaults.standard.synchronize() 
    } 
} 

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { 
    // print("#########################################") 
    //print("didRefreshRegistrationToken") 
    ConnectToFCM() 
} 

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
    print("Recived: \(userInfo)") 
    completionHandler(.newData) 
} 

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
    // print("#########################################") 
    // print("didRegisterForRemoteNotificationsWithDeviceToken") 

    Messaging.messaging().apnsToken = deviceToken 

    // print(Messaging.messaging().apnsToken ?? "No apnsToken") 
    // print(InstanceID.instanceID().token() ?? "No instanceID token") 
} 

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
    // print("#########################################") 
    // print("didFailToRegisterForRemoteNotificationsWithError") 
} 

@available(iOS 10.0, *) 
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void){ 
    let userInfo = notification.request.content.userInfo 
    // Print message ID. 
    print("Message ID: \(userInfo["gcm.message_id"]!)") 
    // Print full message. 
    print("%@", userInfo) 
} 

@available(iOS 10.0, *) 
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Swift.Void){ 
    let userInfo = response.notification.request.content.userInfo 
    // Print message ID. 
    print("Message ID: \(userInfo["gcm.message_id"]!)") 
    // Print full message. 
    print("%@", userInfo) 
} 

// [START receive_message] 
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 
    // 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. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    //print(userInfo) 
} 

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], 
       fetchCompletionHandler completionHandler: @escaping (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. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 
    // Print full message. 
    //print(userInfo) 
    completionHandler(UIBackgroundFetchResult.newData) 
} 
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. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
    Messaging.messaging().shouldEstablishDirectChannel = false 
    //print("Disconnected from FCM.") 
} 
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. 
    ConnectToFCM() 
}**