更新时间:2023-12-03 16:31:52
在您的 AppDelegate.swift
文件中导入 FirebaseMessaging
.AppDelegate
类.didRefreshRegistrationToken
委托方法并获取用户的注册令牌:import FirebaseMessaging
in your AppDelegate.swift
file.AppDelegate
class.didRefreshRegistrationToken
delegate method and get your user's registration token:现在您已准备好向特定用户发送推送通知.发送通知如下:
Now you are ready to send push notification to your specific user. Send notification as below:
func sendPushNotification(payloadDict: [String: Any]) {
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// get your **server key** from your Firebase project console under **Cloud Messaging** tab
request.setValue("key=enter your server key", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: payloadDict, options: [])
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print(response ?? "")
}
print("Notfication sent successfully.")
let responseString = String(data: data, encoding: .utf8)
print(responseString ?? "")
}
task.resume()
}
现在调用上面的函数:
Now call above function as:
let userToken = "your specific user's firebase registration token"
let notifPayload: [String: Any] = ["to": userToken,"notification": ["title":"You got a new meassage.","body":"This message is sent for you","badge":1,"sound":"default"]]
self.sendPushNotification(payloadDict: notifPayload)