2016-05-19 9 views
19

Ho un'applicazione che memorizza la sessione dell'utente in NSUserDefaults. Quando l'applicazione è costretto a chiudere, nella prima verificare se la sessione utente titolare del trattamento lì, nel caso se ci ha inviato alla finestra di avvio come segue:Applicazione di messaggistica cloud che termina l'app

override func viewWillAppear(animated: Bool) { 

    self.view.hidden = true 

    let defaults = NSUserDefaults.standardUserDefaults() 
    if defaults.stringForKey("user") != nil 
    { 

     dispatch_async(dispatch_get_main_queue(), {() -> Void in 
      let viewController:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("vistaInicio") as! ViewControllerInicio 
      self.presentViewController(viewController, animated: true, completion: nil) 
     }) 


    }else 
    { 
    self.view.hidden = false 

    } 

} 

questo ha funzionato senza intoppi me fino ad oggi, quando ho deciso di implementare notifiche push con l'aggiornamento di Firebase seguendo questo tutorial Setting up a Firebase Cloud Messaging Client App on iOS. Il problema si verifica quando ha ucciso l'applicazione e inserire nuovamente dà il seguente codice di errore:

2016-05-19 16:05:27.647: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(full)" 
2016-05-19 16:05:27.659: <FIRMessaging/INFO> FIRMessaging library version 1.1.0 
2016-05-19 16:05:27.831: <FIRMessaging/WARNING> FIRMessaging registration is not ready with auth credentials 
Unable to connect with FCM. Optional(Error Domain=com.google.fcm Code=501 "(null)") 

Screenshot

+0

hai inizializzato correttamente il framework generale di Firebase? –

+0

Sì, il mio AppDelegate è identico a quello di questo esempio [Firebase Messaging Quickstart] (https://github.com/firebase/quickstart-ios/tree/master/messaging). Ricevo correttamente le notifiche, il problema è quando uccido l'applicazione e si riapre un arresto anomalo, quindi riprovo e funziona normalmente. –

risposta

34

Ecco la soluzione,

Prima Carica i certificati necessari a Firebase Console Poi, nel tuo app abilitare le notifiche push e le modalità di background -> Notifiche remote

Successivamente in App Delegate utilizzare il codice seguente (specificare la linea complessa):

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    registerForPushNotifications(application) 
    // Override point for customization after application launch. 
    // Use Firebase library to configure APIs 
    FIRApp.configure() 
    return true 
} 

func registerForPushNotifications(application: UIApplication) { 
    let notificationSettings = UIUserNotificationSettings(
     forTypes: [.Badge, .Sound, .Alert], categories: nil) 
    application.registerUserNotificationSettings(notificationSettings) 
} 

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

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { 
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) 
    var tokenString = "" 

    for i in 0..<deviceToken.length { 
     tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) 
    } 

    //Tricky line 
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown) 
    print("Device Token:", tokenString) 
} 
+0

Questo risolve il problema, non dà più l'errore. Ora come posso controllare il download dei dati quando l'applicazione è in background? –

+0

Questo lo ha risolto anche per me! Grazie! – Jorsh

+3

Hai la versione dell'obiettivo-c di questo codice? –

5

Non dimenticate in AppDelegate:

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

    registerForPushNotifications(application) 
    FIRApp.configure() 

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

    // Override point for customization after application launch. 
    return true 
    } 

func registerForPushNotifications(application: UIApplication) { 
     let settings: UIUserNotificationSettings = 
     UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
     application.registerForRemoteNotifications() 
    } 


    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
        fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
    print("===== didReceiveRemoteNotification ===== %@", userInfo) 
    } 


func tokenRefreshNotificaiton(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. 
    connectToFcm() 
    } 

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

Assicurati anche di fare in Info.plist: FirebaseAppDelegateProxyEnabled = NO

non so per ora, ma ho avuto la print(...) in didReceiveRemoteNotification ma non ottieni il popup. Trasmetto il messaggio da Firebase -> Console -> Notifica -> dispositivo singolo e copiare qui il token, che ho ricevuto da Xcode Console ->func tokenRefreshNotificaiton

+0

pezzo mancante: '.addObserver', mi ha salvato! –

+0

@ Mr.Bista. Per favore mi guidi sulla notifica push, lavorando con FCM .Sono in grado di inviare un messaggio dal server ma il metodo di notifica non sta chiamando. Si prega di verificare la mia domanda http: // stackoverflow.it/questions/41198651/xcode-8-1-push-notifications-in-swift-2-3-with-firebase-integration-not-getting –

4

risposta è corretta questi sono i passi, ma anche si prega di controllare il dispositivo tempo . Dal momento che se la tua data e ora è troppo lontana non funzionerà

2

Dopo aver controllato per tre volte l'intera integrazione, per me il problema era che il dispositivo di prova aveva la data cambiata con una settimana di anticipo. Probabilmente l'SDK FCM esegue alcuni controlli basati sulla data.

L'errore potrebbe essere meno generico sul lato Firebase, poiché ho perso quasi un giorno alla ricerca di una soluzione. Spero che questo ti aiuti.

+0

Grazie mille, questo era esattamente il mio problema! – manisha