我的两部 iPhone 中都有一个简单的应用程序。我的应用程序只包含一个按钮,我想在单击该按钮时将推送通知发送到另一台设备。我已经在 firebase 控制台中创建了项目。
<pre><code>
In ViewController :-
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func sendPushNotification(to token: String, title: String, body: String) {
// Set up the message content
let message = ["to": token,
"priority": "high",
"notification": ["title": title,
"body": body,
"badge": 1,
"sound": "default"]] as [String: Any]
// Serialize the message to JSON
guard let jsonData = try? JSONSerialization.data(withJSONObject: message, options: []) else {
print("Failed to serialize message to JSON")
return
}
// Create the request object
guard let url = URL(string: "https://fcm.googleapis.com/fcm/send") else {
print("Failed to create URL object")
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=<YOUR_SERVER_KEY>", forHTTPHeaderField: "Authorization")
request.httpBody = jsonData
// Send the request
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Failed to send notification: \(error.localizedDescription)")
return
}
print("Notification sent successfully")
}
task.resume()
}
@IBAction func sendNotification(_ sender: Any) {
print("gfcyfc")
sendPushNotification(to: "5277df78e6354334eb84d5644c349d34c83f102d9abfbe5843c7cac5af1f27e0", title: "Hello", body: "Hello How are your")
}
}
In App delegate :-
import UIKit
import FirebaseCore
import FirebaseMessaging
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { success, _ in
guard success else{ return }
print("Registration Successful")
}
application.registerForRemoteNotifications()
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
messaging.token { token, _ in
guard let token = token else { return }
print("Tokennnnnnnnn\(token)")
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert device token to string format
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
print("Device token: \(deviceTokenString)")
Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for remote notifications: \(error.localizedDescription)")
}
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
}
</code></pre>
当我点击一台设备上的按钮时如何将推送通知发送到另一台设备 我尝试了很多方法,但始终无济于事 我收到一条错误消息“*在检索发件人 ID ‘230481463908’的 FCM 令牌之前未设置 APNS 设备令牌。设置 APNS 设备令牌后,请务必重新检索 FCM 令牌。 “