2016-09-11 5 views
3

Мне нравится ниже в Swift 2. Но он не работает в Swift 3. Как я могу это предоставить? Если кто-то объяснит это, было бы здорово.Swift 3 - Уведомление Push-Firebase, как я могу это сделать?

didFinishLaunchingWithOptions

let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) 
application.registerForRemoteNotifications() 

и

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { 
    if notificationSettings.types != .None { 
     application.registerForRemoteNotifications() 
    } 
} 

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { 

    print("Meesage ID \(userInfo["gcm_message_id"]!)") 
    print(userInfo) 

} 

я могу сделать простой локальной уведомление, но я не мог удаленный толчок уведомление от Firebase.

Я попытался

UNUserNotificationCenter.currentNotificationCenter().delegate = self 

UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Alert, .Badge, .Sound]) { (success, error:NSError?) in 

     if success { 
      print("Notification access true!") 
      application.registerForRemoteNotifications() 
     } 
     else { 
      print(error?.localizedDescription) 
     } 

} 

и

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { 

    print("Meesage ID \(userInfo["gcm_message_id"]!)") 
    print(userInfo) 

} 

до сих пор не работает.

+0

Имя методов делегата слегка изменились. Набрав имя каждого метода, вы должны увидеть соответствующий метод в Swift 3 в качестве предложения. – Callam

ответ

9

Имена методов AppDelegate немного изменились, и была введена система UserNotifications. Вы должны использовать эту фреймворк для уведомлений в iOS 10 и выше, поскольку другие методы устаревают.

import UserNotifications 

... 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    ... 

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

     UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in 
      // Enable or disable features based on authorization. 
     } 

     application.registerForRemoteNotifications() 

     return true 
    } 

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) ->()) { 

     print("Message ID \(userInfo["gcm.message_id"]!)") 
     print(userInfo) 
    } 

    ... 
} 

Registering for Push Notifications in Xcode 8/Swift 3.0?

1

Это очень важно помнить, что могут быть различные устройства, которые работают различные версии IOS, и они могут иметь различные возможности уведомления. Я понимаю, что предыдущий ответ указывает на правильное направление.

Мы должны указать import FirebaseInstanceID, если мы хотим получить экземпляр или уведомления о событиях. Такие уведомления похожи на те, которые появляются, когда кто-то пересматривает наш пост или любит сообщение или уведомление о сообщении.

Однако, если кто-то ищет полный код, который входит в функцию didFinishLaunchingWithOptions в AppDelegate, здесь:

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

    FIRApp.configure() 

    if #available(iOS 10.0, *) { 
     let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound] 
      UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
      authOptions, completionHandler: {_,_ in }) 
    } else { 
     // Fallback on earlier versions 
     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
     application.registerForRemoteNotifications() 
    } 

    application.registerForRemoteNotifications() 

    // Add observer for InstanceID token refresh callback. 
NSNotificationCenter.defaultCenter().addObserver(self, 
    selector: #selector(self.tokenRefreshNotification), 
    name: kFIRInstanceIDTokenRefreshNotification, 
    object: nil) 

    return true 
} 

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
       fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
// This is required if you are receiving a notification message while your app is in the background, which is the most common case!! 

print("Message ID: \(userInfo["gcm.message_id"]!)") 

print("%@", userInfo) 
} 


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

connectToFcm() 
} 


func connectToFcm() { 
FIRMessaging.messaging().connectWithCompletion { (error) in 
    if (error != nil) { 
    print("Unable to connect with FCM. \(error)") 
    } else { 
    print("Connected to FCM.") 
    } 
} 
} 
func applicationDidBecomeActive(application: UIApplication) { 
connectToFcm() 
} 
func applicationDidEnterBackground(application: UIApplication) { 
FIRMessaging.messaging().disconnect() 
print("Disconnected from FCM.") 
} 
1

Это то, что работает для меня Xcode 8, Swift 3.

Внутри didFinishLaunchingwithOptions FUNC в AppDelegate.swift

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

      // 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() 

     FIRApp.configure() 

     // [START set_messaging_delegate] 
     FIRMessaging.messaging().remoteMessageDelegate = self 
     // [END set_messaging_delegate] 

И делегаты, необходимые для получения уведомлений от firebase:

@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. 
     print("Message ID: \(userInfo["gcm.message_id"]!)") 

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

     let aps = userInfo["aps"] as! [String: Any] 
     let notificationMessage = aps["alert"] as! String // processed content from notificaton 

    } 

} 

extension AppDelegate : FIRMessagingDelegate { 
    // Receive data message on iOS 10 devices. 
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { 
     print("%@", remoteMessage.appData) 

    } 
} 
Смежные вопросы