swift firebase远程通知未接收,xCode 9.0

时间:2017-09-08 20:47:15

标签: swift firebase notifications

大家好日子。第一篇文章,所以我会尽我所能: 我一直在使用stackoverflow一段时间试图用现有的问题解决这个问题,但没有成功。

我正在尝试使用xCode 9.0 beta 5进行简单的Firebase远程推送通知。从consol中,它显示已完成,但我没有看到任何通知进入我的应用。我检查了证书,快速功能等,一切似乎都很好。仍然没有成功。这可能是AppDelegate代码。我真的不知道从哪里开始所以任何帮助都会受到赞赏。我实际上有一个非常简单的版本正在发布swift的版本,它也不再工作,所以我相信它与代码有关:

类AppDelegate:UIResponder,UIApplicationDelegate,CLLocationManagerDelegate,MessagingDelegate,UNUserNotificationCenterDelegate {

var window: UIWindow?
var manager = CLLocationManager()
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    // Added by Ryan to support FB login:
    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

    // Added by Ryan to support Twitter login:
    Twitter.sharedInstance().start(withConsumerKey:"ecd84HTwPAdHMhCENbM1o2IfQ", consumerSecret:"W3HmRzYpBOMmtDpHn6J3LCdV67VVeqkz87FvqOzSSRLrvZI6Ju")

    // Set the CLLocationManager accuracy:
    manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    manager.allowsBackgroundLocationUpdates = true
    manager.pausesLocationUpdatesAutomatically = false
    manager.distanceFilter = USER_DISTANCE_FILTER // meters until postion updated

    // Initialize Firebase Remote Notifications:
    // Request Authorizations:
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
        if err != nil {
            print(err!)
            return
        } else {
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    // Configure Firebase:
    FirebaseApp.configure()

    UNUserNotificationCenter.current().delegate = self
    Messaging.messaging().delegate = self
    connectToFMC()

    return true
}

func connectToFMC() {
    // Establish a direct connection the the FMC (Firebase Messaging Controller):
    Messaging.messaging().shouldEstablishDirectChannel = true
}


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.

    print("Entering Background")
    self.manager.startUpdatingLocation()
}

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.

    var geoFireActiveAgents: GeoFire!
    var geoFireActiveAgentsRef: DatabaseReference!

    geoFireActiveAgentsRef = DataService.ds.REF_ACTIVEAGENTS
    geoFireActiveAgents = GeoFire(firebaseRef: geoFireActiveAgentsRef)

    // Make a direct connection to Firebase Messaging Controller for Remote messaging:
    connectToFMC()

    // When the app comes out of sleep, we need to update the location data to the global variable and the database in case the user moved while asleep:
    if CLLocationManager.locationServicesEnabled() {

        // log the active position to the Primary User Info:
        if let activeLocation = manager.location {
            PrimaryUserInfo.primUser.activeLocation = activeLocation
            if let userID = Auth.auth().currentUser?.uid {
                if let userLatitude = PrimaryUserInfo.primUser.activeLocation.coordinate.latitude as Optional {
                    if let userLongitude = PrimaryUserInfo.primUser.activeLocation.coordinate.longitude as Optional {

                        // If the user is an active Agent, log his/her location in GeoFire:
                        if PrimaryUserInfo.primUser.activeAgent {

                            geoFireActiveAgents.setLocation(CLLocation(latitude: userLatitude, longitude: userLongitude), forKey: userID)

                            // Add a timestamp to see when the Agent was last active:
                            let timeStamp = Date().timeIntervalSince1970
                            let values = ["timestamp": timeStamp] as [String : Any]
                            DataService.ds.REF_ACTIVEAGENTS.child(userID).updateChildValues(values, withCompletionBlock: { (err, ref) in
                                if err != nil {
                                    print(err!)
                                }
                            })
                        }
                    }
                }
            }
        }
    }
}

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

    print("Application Terminating")

    // Remove the active agent from the Firebase Database:
    DataService.ds.REF_ACTIVEAGENTS.child(PrimaryUserInfo.primUser.userID).removeValue()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations location: CLLocation){
    // Send background location to Firebase Database when there is a significant location change:

    self.sendBackgroundLocationToServer(location: location)
}

func sendBackgroundLocationToServer(location: CLLocation) {
    // This section updates the Firebase Database location while app is in the background.
    // It purposefuly uses a background task to 'wake up' and spit out the data.

    var bgTask = UIBackgroundTaskIdentifier()

    bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        UIApplication.shared.endBackgroundTask(bgTask)
    })

    var userLatitude = CLLocationDegrees()
    var userLongitude = CLLocationDegrees()

    if CLLocationManager.authorizationStatus() == .authorizedAlways {
        userLatitude = (manager.location?.coordinate.latitude)!
        userLongitude = (manager.location?.coordinate.longitude)!

        let geoFireActiveAgents: GeoFire!
        let geoFireActiveAgentsRef: DatabaseReference!
        geoFireActiveAgentsRef = DataService.ds.REF_ACTIVEAGENTS
        geoFireActiveAgents = GeoFire(firebaseRef: geoFireActiveAgentsRef)

        let userID = PrimaryUserInfo.primUser.userID
        geoFireActiveAgents.setLocation(CLLocation(latitude: userLatitude, longitude: userLongitude), forKey: userID)
    }

    if (bgTask != UIBackgroundTaskInvalid)
    {
        UIApplication.shared.endBackgroundTask(bgTask)
        bgTask = UIBackgroundTaskInvalid
    }
}

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // New Token automatically established:
    let newToken = InstanceID.instanceID().token()
    print("newToken = \(newToken!)")
    connectToFMC()
}

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

    // custom code to handle push while app is in the foreground
    print("Handle push from foreground\(notification.request.content.userInfo)")

    let dict = notification.request.content.userInfo["aps"] as! NSDictionary
    let d : [String : Any] = dict["alert"] as! [String : Any]
    let body : String = d["body"] as! String
    let title : String = d["title"] as! String
    print("Title:\(title) + body:\(body)")
    self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)

}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}

func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
    window.rootViewController?.present(alert, animated: false, completion: nil)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    if let token = InstanceID.instanceID().token() {
        print("Token: \(token)")
    }
}

}

0 个答案:

没有答案