为啥推送通知不能在 iOS 中使用 Firebase 从设备到设备?
Posted
技术标签:
【中文标题】为啥推送通知不能在 iOS 中使用 Firebase 从设备到设备?【英文标题】:Why the push notification don‘t work in iOS with Firebase from device to device?为什么推送通知不能在 iOS 中使用 Firebase 从设备到设备? 【发布时间】:2019-08-06 19:59:15 【问题描述】:我已经创建了生产标识符和所有这些东西,它已经工作了,但后来某个时候突然它不再工作了。而且我的代码中的通知区域没有任何变化。
来自 Firebase 云消息传递 - 测试发送工作正常。但不是从设备到设备。
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
import AVFoundation
import GoogleMobileAds
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
var window: UIWindow?
static let NOTIFICATION_KEY = "https://gcm-http.googleapis.com/gcm/send"
static var DEVICE_ID = String()
static let SERVER_KEY = "AAAACucgXz8:APA91bE_vEyKiqR34sruY2f5tetjj_DrwVi42v9tL015tLEOZmwBh-q7oWsNXUrpR0S9XBCrbxMJtgUu70xNAyDeouNvxn1kHKll2Dcwzxbf40lbappxs-o6IDvHVvEajzX5Dzsq8MW8"
static var EXITAPP = Bool()
static var LIKESCOUNTER = Int()
var dateForm = DateFormatter()
var timeFormatter = DateFormatter()
static var INSERTTIME = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
// Override point for customization after application launch.
FirebaseApp.configure()
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible() //Damit wir die ganzen Views selber bearbeiten können.
window?.rootViewController = UINavigationController(rootViewController: ViewController())
if #available(ios 10.0, *)
UNUserNotificationCenter.current().delegate = self
let option: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: option) (bool, err) in
application.registerForRemoteNotifications()
UIApplication.shared.applicationIconBadgeNumber = 0
GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
if #available(iOS 9.0, *)
application.isStatusBarHidden = true //HIDE STATUS BAR
return true
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.
insertOnlineActivity(online: false)
connectToFCM()
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.
AppDelegate.EXITAPP = true
// if AppDelegate.INSERTTIME
// insertLastLikedTime()
//
insertOnlineActivity(online: false)
connectToFCM()
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.
insertOnlineActivity(online: true)
connectToFCM()
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.
insertOnlineActivity(online: true)
connectToFCM()
func applicationWillTerminate(_ application: UIApplication)
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
guard let newToken = InstanceID.instanceID().token() else return
AppDelegate.DEVICE_ID = newToken
connectToFCM()
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
let notification = response.notification.request.content.body
print(notification)
completionHandler()
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
guard let newToken = InstanceID.instanceID().token() else return
//let newToken = deviceToken.map String(format: "%02.2hhx", $0) .joined()
AppDelegate.DEVICE_ID = newToken
connectToFCM()
Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
func connectToFCM()
Messaging.messaging().shouldEstablishDirectChannel = true
【问题讨论】:
@SanjeevS 抱歉,如果你看,我在我的个人资料中添加了一个新问题,一个问题中包含所有内容。 【参考方案1】:这就是我调用通知的方式
fileprivate func setUpPushNotifications(fromDeviceID: String)
let message = self.userName + " has sent you a voice message."
let title = "New Message"
let toDeviceID = fromDeviceID
var headers:HTTPHeaders = HTTPHeaders()
headers = ["Content-Type":"application/json","Authorization":"key=\(AppDelegate.SERVER_KEY)"]
let notifications = ["to" : "\(toDeviceID)" , "notification":["body":message,"title":title,"badge":1,"sound":"default"]] as [String : Any]
request(AppDelegate.NOTIFICATION_KEY as URLConvertible, method: .post as HTTPMethod, parameters: notifications, encoding: JSONEncoding.default, headers: headers).response (response) in
print(response)
【讨论】:
根据我的其他评论,这不会作为答案发布,因为您正在为您的问题提供更多信息。您应该复制此代码,删除此答案并使用代码更新您的问题。以上是关于为啥推送通知不能在 iOS 中使用 Firebase 从设备到设备?的主要内容,如果未能解决你的问题,请参考以下文章