編輯:react-native現在默認實現這種行爲。有趣的部分是現在返回設備令牌的註冊事件的事件監聽器。程序現在非常簡單。只需看看docs也可以查看JWindey的答案。在他們中有一些非常重要的點需要實際觸發事件。
經過一段時間和大量嘗試,我們今天想出了一個答案。這是我們的解決方案,它似乎工作得很好。
我們使用下面的資源:
按照分析指南進行推送通知(https://parse.com/tutorials/ios-push-notifications),並正確設置所有內容(配置文件,certificat es等)。稍後使用react-native-remote-push組件,您不必按照步驟5和步驟6.
現在將react-native-remote-push添加到您的項目中。我們必須對代碼進行一些小的調整(主要處理遺留的objC代碼),但這可能取決於您自己的項目。
我們的項目有一些「開始頁面」,每次打開應用程序時都會顯示。在此頁面上,我們處理推送通知權限以及註冊設備令牌和監聽器以進行推送通知。我們的目標是模仿與解析iOS SDK相同的行爲。
我們需要先註冊設備並訂閱推送通道。 react-native-remote-push允許我們處理權限並接收設備令牌。然後,我們繼續使用此設備令牌通過Rest API註冊此安裝。此代碼是我們的componentDidMount()調用的一部分。
var PushManager = require('./RemotePushIOS');
var registerInstallation = require('./Installation');
componentDidMount() {
PushManager.requestPermissions(function(err, data) {
if (err) {
console.log("Could not register for push");
} else {
registerInstallation({
"deviceType": "ios",
"deviceToken": data.token,
"channels": ["global"]
});
}
});
PushManager.setListenerForNotifications(this.receiveRemoteNotification);
}
PushManager是react-native-remote-push中的必需組件,registerInstallation是包含Rest API調用的函數。
/**
* registers an installation
* data should look like the following:
* {
* "deviceType": "ios", // or "android"
* // if android is targeted set
* // "pushType": "gcm",
* // "GCMSenderId": "56712320625545", // whatever the later means
* "deviceToken": "29e32a686fd09d053e1616cb48",
* "channels": [
* ""
* ]
* };
* for more information visit:
* https://www.parse.com/docs/rest#installations-uploading
*/
var registerInstallation = function(data) {
var url = "https://api.parse.com";
url += "/1/installations";
fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'X-Parse-Application-Id': PARSE_APP_ID,
'X-Parse-REST-API-Key': PARSE_REST_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(processStatus)
.then(parseJson)
.catch(error);
};
module.exports = registerInstallation;
「processStatus」,「parseJson」和「error」只是處理API調用結果的一些小函數。如有必要,我可以提供更多細節。這個函數允許我們通過「data」對象添加大量信息,例如userid,app版本,解析版本等,就像您從iOS SDK中習慣的那樣。我們現在只有一個基本的例子,但在這個基礎上擴展應該很容易。這一步對我們來說非常重要,因爲我們需要將每個安裝與特定用戶相關聯。
您現在應該能夠收到推送通知。您可以在充當監聽器的「receiveRemoteNotification」函數中處理它們。在react-native-remote-push組件的網站上提供了一個基本功能。
我希望我能分享一些關於這個話題的見解。如果我應該詳細說明某些部分,我會很樂意添加更多信息。
我本指南[鏈接](https://www.parse.com/docs/push_guide#top/iOS) – rob180
非常感謝您的回覆做到了。本指南的JavaScript部分告訴我,它主要用於發送推送,但不能接收推送(可以通過react-native處理)或訂閱設備推送。 因爲我想盡量減少項目中的objc和swift代碼,所以這似乎不能解決我的問題。 (注意:我之前都是這麼做的,現在的挑戰是轉移到反應本地) – MrMuetze
@MrMuetze有什麼好運氣?你有工作嗎?如果是,請分享如何? – Nachiket