hma*_*ali 6 push-notification ios firebase swift3 firebase-cloud-messaging
我是新的 iOS 开发人员。
我正在使用 firebase 并且我正在尝试制作一个聊天应用程序,当他/她收到任何消息时我需要通知用户。为此,我尝试了 firebase 推送通知,但无法在其他用户发送消息时触发它们。我发现的唯一方法是使用 firebase 控制台发送推送通知,但它不满足我的要求。我刚刚配置了本地通知。请指导我如何在不使用 firebase 控制台的情况下触发推送通知。
经过近1个月的努力,终于找到了解决方案。
这些是基本步骤
首先,您需要确保您拥有一个活跃的苹果开发者帐户
只需在此处启用 Firebase 推送通知即可 ,即此步骤的 YouTube 视频链接
我发现很难以其确切的形式发布代码,但代码从这里开始
const functions = require('firebase-functions');
const admin =require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const ref=admin.database().ref();
exports.sendNotification=functions.https.onRequest((req,res) =>{
const id = req.query.id
const title = req.query.title
const message = req.query.message
const key = req.query.key
// admin.database.ref()
const payload ={
notification: {
title: title,
body: message,
//badge: '1',
sound: 'default',
}
};
console.log('Param [key] is '+key);
const keys = [] ;
ref.child('keys').once('value')
.then(snap => {
snap.forEach(childSnap => {
const loopKey=childSnap.val().key;
keys.push(loopKey);
})
return keys;
})
.then(keys=>{
//console.log('Keys in database : '+keys.join());
if(keys.indexOf(key)>-1)
{
if(!key || !id || !message)
{
res.status(400).send('Bad request');
}
else{
ref.child('users').child(id).child('fcmToken').once('value')
.then(snapshot => {
if (snapshot.val()){
const token = snapshot.val()
console.log(token);
return admin.messaging().sendToDevice(token,payload).then(response =>{
res.status(200).send('Notification sent')
});
}
});
}
}
else
{
console.log("In-valid key : "+key);
res.status(400).send('Bad request');
}
})
.catch(error => {
res.send(error)
});
});
Run Code Online (Sandbox Code Playgroud)
至此结束
这是将您的 fcm 存储到数据库的功能
func postToken(token: String, id: String){
print("FCM Token \(token)")
let ref = Database.database().reference().child("users").child(id)
ref.child("fcmToken").setValue(token)
}
Run Code Online (Sandbox Code Playgroud)
这是我用来触发此 API 的函数
func sendNotification(id: String, title: String, message: String){
var url = "your URL"
var urlComponents = NSURLComponents(string: url)
urlComponents?.queryItems = [
URLQueryItem(name: "key", value: self.apiKey),
URLQueryItem(name: "id", value: id),
URLQueryItem(name: "title", value: title),
URLQueryItem(name: "message", value: message)
]
Alamofire.request((urlComponents?.url)!).responseJSON { (response) in
print(response.response)
print(response.response)
print(response.result)
}
}
Run Code Online (Sandbox Code Playgroud)
上面的API是根据我的数据库结构编写的。您可以根据自己的结构轻松更改它。
完成此操作后,您将能够在点击 URL 后发送通知
希望它能为大家提供一个好主意,让您可以根据需要使用自己的通知。
归档时间: |
|
查看次数: |
1813 次 |
最近记录: |