无法从后端Swift获取推送通知

时间:2019-07-25 10:08:33

标签: ios swift push-notification

我正在尝试在应用程序中实现推送通知,并且我在应用程序中使用了Firebase推送通知服务。我在应用程序中成功实现了它。现在我面临的问题是我需要显示来自服务器的推送通知。这是从php服务器接收通知的代码

func pushNotificationsApi() {

    let fcmToken = UserDefaults.standard.string(forKey: "firebaseToken") ?? ""
    print(fcmToken)

    let param: [String:Any] = ["user_id": userDetail.getUserID(),
                               "token_id": fcmToken,
                               "device_type": "iOS",
                               "device_id": AppDelegate.shared.deviceId]
    print(param)
    Alamofire.request(Constants.BASE_URL+"push_device_registration.php", method: .post, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            if let json = response.result.value as? [String:Any] {
                print(json)

            }
            break

        case .failure(_):
            print("Error")
            break

        }
    }

}

从json获得成功响应后,仍然无法从后端获取通知。

这是AppDelegate类中的代码:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("The device token is.....\(deviceToken.base64EncodedString())")
    Messaging.messaging().apnsToken = deviceToken
}


func registerForFirebaseNotification(application: UIApplication) {
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()
}

接收令牌

    //MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    self.firebaseToken = fcmToken
    let token: String = firebaseToken
    UserDefaults.standard.set(token, forKey: "firebaseToken")
    UserDefaults.standard.synchronize()
    print("Firebase token: \(fcmToken)")
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("didReceive remoteMessage: \(remoteMessage)")
}

//UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("APNs received with: \(userInfo)")
    self.handleNotification(userInfo: userInfo as! [String : Any])
}


func handleNotification(userInfo: [String:Any]) {
    DispatchQueue.delay(1.0, closure: {
        if let mainNav = AppDelegate.shared.window?.rootViewController as? UINavigationController {
            let storyboard = UIStoryboard(name: "Home", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as! NotificationVC
            mainNav.pushViewController(vc, animated: true)
        }
    })
}

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("The device token is.....\(deviceToken.base64EncodedString())")
    Messaging.messaging().apnsToken = deviceToken
}

didFinishLaunching方法中的代码

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



    IQKeyboardManager.shared.enable = true

    let deviceID = UIDevice.current.identifierForVendor!.uuidString
    print("====Device Id ====  \(deviceID) =============")
    self.deviceId = deviceID
    let deviceid: String = deviceID
    UserDefaults.standard.set(deviceid, forKey: "deviceId")
    UserDefaults.standard.synchronize()
    FirebaseApp.configure()
    self.registerForFirebaseNotification(application: application)
    Messaging.messaging().delegate = self


    return true
}

我正在从Firebase控制台接收推送通知,但无法从php服务器获取通知。我不明白我在做什么错。请帮忙吗?

0 个答案:

没有答案