Кордова/Phonegap iOS Parse-Push Plugin
Я потратил много времени, чтобы найти правильный плагин cordova для разбора push-уведомлений для платформ Android и iOS.
Мои требования:
- Получить оповещение о синтаксическом разборе (как в Android, так и в iOS)
- Возможность хранения всех входящих push-уведомлений в локальном хранилище Sqlite для мобильных устройств.
Я пробовал все приведенные ниже синтаксические плагины для плагинов для Android и iOS.
Для Android: Все вышеперечисленные плагины отлично работают, чтобы выполнить мои вышеупомянутые требования.
Для iOS: Работает только 1-й плагин i.e https://github.com/avivais/phonegap-parse-plugin. И это тоже я не смог сохранить уведомления в локальном хранилище sqlite. Это означает, что выполняется только мое первое требование, но не мое второе требование.
Все страницы github оставшихся плагинов (то есть 2nd, 3rd, 4th) заявляют, что:
"Обратите внимание, что я работал только с Android-аспект этой вилки. Сторона iOS еще не обновлена".
Есть ли какой-либо плагин, который будет работать на платформах Android и iOS для выполнения моих 2 требований?
(или)
Если общий плагин для обеих платформ отсутствует, тогда как я могу хранить входящие плагины в iOS sqlite?
Пожалуйста, помогите мне. Спасибо заранее.
Ответы
Ответ 1
Я поддерживаю https://github.com/taivo/parse-push-plugin
Похоже, ты поймал мою вилку в зачаточном состоянии. Я поднял его, когда вилка вверх по течению казалась застойной на некоторое время, и в то время я только обратился к аспекту Android. С тех пор я предоставил полную поддержку iOS. И он работает для parse-server, а также извлечения parse.com. Я также сделал один лучше и сделал установку только вопрос
cordova add https://github.com/taivo/parse-push-plugin
и написание нескольких тегов config.xml
для указания URL-адреса сервера и идентификатора приложения.
При настройке плагина это должно устранить большую боль при ручном возиться с Android Manifest, Java и Objective C.
Теперь он должен соответствовать или превышать ваши требования. Чтобы получать push-уведомление и хранить в sqlite, все, что вам нужно сделать, это установить обработчик событий в javascript. Не забудьте обернуть его каким-либо устройством, готовым или обработанным платформой, чтобы обеспечить правильную загрузку плагина.
$ionicPlatform.ready(function(){
if(window.ParsePushPlugin){
ParsePushPlugin.on('receivePN', function(pn){
console.log('yo i got this notif:' + JSON.stringify(pn) );
//
// do your sqlite storage here
//
});
}
});
Ответ 2
Вас может заинтересовать Azure Push Notifications. Он объединяет обе службы Push-уведомлений, поэтому вы можете отправлять сообщения на оба устройства из одной центральной точки.
Я цитирую:
Центры уведомлений Масштабируемое кросс-платформенное решение для отправки push уведомления на мобильные устройства, Notification Hubs хорошо работают с Приложения Кордовы. Узлы уведомлений управляют регистрациями с каждым ШПС. Что еще более важно, Notification Hubs позволяют создавать шаблоны чтобы вы могли отправлять сообщения всем зарегистрированным устройствам, независимо от платформы, только с одной строкой кода. Вы также можете использовать теги для отправки целевых уведомлений только на устройства с конкретными регистрации. Дополнительные сведения о концентраторах уведомлений см. В разделе Azure на сайте aka.ms/nkn4n4.
Здесь у меня есть вспомогательный класс для регистрации вашего устройства с помощью службы pushnotification. Для отправки push-уведомлений вы можете использовать лазурный портал и отправлять стильные push-уведомления в формате json.
var Pushman = {
Initialize: function (hubConnString, hubName, gcmSenderId, callbackRegistered, callbackUnRegistered, callbackInlineNotification, callbackBackgroundNotification, callbackError) {
//store connection and callback information on app startup for Push Registration later
Pushman.HubConnectionString = hubConnString;
Pushman.HubName = hubName;
Pushman.GcmSenderId = gcmSenderId;
//callbacks
Pushman.RegisteredCallback = callbackRegistered;
Pushman.UnRegisteredCallback = callbackUnRegistered;
Pushman.NotificationForegroundCallback = callbackInlineNotification;
Pushman.NotificationBackgroundCallback = callbackBackgroundNotification;
Pushman.ErrorCallback = callbackError;
},
RegisterForPushNotifications: function (tags) {
//setup Azure Notification Hub registration
Pushman.Hub = new WindowsAzure.Messaging.NotificationHub(Pushman.HubName, Pushman.HubConnectionString, Pushman.GcmSenderId);
Pushman.Hub.registerApplicationAsync(tags).then(Pushman.onRegistered, Pushman.onError);
//setup PushPlugin registration
Pushman.Push = window.PushNotification;
var push;
//register depending on device being run
if (device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos") {
//android
push = Pushman.Push.init(
{ "android": { "senderID": Pushman.GcmSenderId } }
);
push.on('registration', Pushman.onRegistered);
push.on('notification', Pushman.onAndroidNotification);
push.on('error', Pushman.onError);
} else {
//iOS
push = Pushman.Push.init(
{ "ios": { "alert": "true", "badge": "true", "sound": "true" } }
);
push.on('registration', Pushman.onRegistered);
push.on('notification', Pushman.onIOSNotification);
push.on('error', Pushman.onError);
}
},
UnRegisterForPushNotifications: function () {
if (Pushman.Hub != null) {
//dont pass through error handler
//unreg azure
Pushman.Hub.unregisterApplicationAsync()
.then(Pushman.onUnRegistered, null);
//unreg native
Pushman.Push.unregister(Pushman.onUnRegistered, null);
}
},
onRegistered: function (msg) {
Pushman.log("Registered: " + msg.registrationId);
//only call callback if registrationId actually set
if (msg.registrationId.length > 0 && Pushman.RegisteredCallback != null) {
Pushman.RegisteredCallback(msg);
}
},
onUnRegistered: function () {
Pushman.log("UnRegistered");
if (Pushman.UnRegisteredCallback != null) {
Pushman.UnRegisteredCallback();
}
},
onInlineNotification: function (msg) {
Pushman.log("OnInlineNotification: " + msg);
if (Pushman.NotificationForegroundCallback != null) {
Pushman.NotificationForegroundCallback(msg);
}
},
onBackgroundNotification: function (msg) {
Pushman.log("OnBackgroundNotification: " + msg);
if (Pushman.NotificationBackgroundCallback != null) {
Pushman.NotificationBackgroundCallback(msg);
}
},
onColdStartNotification: function (msg) {
Pushman.log("OnColdStartNotification: " + msg);
if (Pushman.NotificationBackgroundCallback != null) {
Pushman.NotificationBackgroundCallback(msg);
}
},
onError: function (error) {
Pushman.log("Error: " + error);
if (Pushman.ErrorCallback != null) {
Pushman.ErrorCallback(error);
}
},
onAndroidNotification: function (e) {
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
Pushman.onRegistered("Registered");
}
break;
case 'message':
if (e.foreground) {
//if this flag is set, this notification happened while app in foreground
Pushman.onInlineNotification(e.payload.message);
} else {
//otherwise app launched because the user touched a notification in the notification tray.
if (e.coldstart) {
//app was closed
Pushman.onColdStartNotification(e.payload.message);
}
else {
//app was minimized
Pushman.onBackgroundNotification(e.payload.message);
}
}
break;
case 'error':
Pushman.onError(e.msg);
break;
default:
Pushman.onError("Unknown message");
break;
}
},
onIOSNotification: function (event) {
//TODO: not sure how ios works re cold start vs inline msg types?
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.badge) {
Push.setApplicationIconBadgeNumber(app.successHandler, app.errorHandler, event.badge);
}
},
tokenHandler: function (result) {
// iOS - not sure its use though appears somewhat important
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
alert('device token = ' + result);
},
log: function (msg) {
console.log(msg);
},
}
///"class" variables - not sure how to put them into the js "class"
Pushman.Push = null;
Pushman.Hub = null;
Pushman.HubConnectionString = null;
Pushman.HubName = null;
Pushman.GcmSenderId = null;
Pushman.NotificationForegroundCallback = null;
Pushman.NotificationBackgroundCallback = null;
Pushman.RegisteredCallback = null;
Pushman.UnRegisteredCallback = null;
Pushman.ErrorCallback = null;
Я сам этого не писал, все кредитует этот парень.
Затем вам просто нужно инициализировать плагин при запуске приложения:
//azure notificationshub connection information
notificationHubPath = "notificationhub name";
connectionString = "notificatin hub connectionstring";
//sender id for google cloud services
var senderIdGCM = "sender id from google gcm";
//tag registration (csv string), can be empty but not undefined
var registrationTagsCsv = ""; //test1, test2
var app = {
Initialize: function () {
//reg for onload event
this.AppStart();
},
AppStart: function () {
"use strict";
document.addEventListener('deviceready', app.onLoad, false);
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener('pause', onPause.bind(this), false);
document.addEventListener('resume', onResume.bind(this), false);
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
},
onLoad: function () {
app.log("Initializing...");
//setup push notifications
Pushman.Initialize(connectionString, notificationHubPath, senderIdGCM,
app.onNotificationRegistered, app.onNotificationUnRegistered,
app.onNotificationInline, app.onNotificationBackground, app.onNotificationError);
//hookup cmd buttons
app.registerForPush();
//$("#register").click(app.registerForPush);
//$("#unregister").click(app.unRegisterForPush);
app.onAppReady();
},
registerForPush: function (a, c) {
app.log("Registering...");
//register for tags
Pushman.RegisterForPushNotifications(registrationTagsCsv);
},
unRegisterForPush: function (a, c) {
app.log("UnRegistering...");
//register for tags
Pushman.UnRegisterForPushNotifications();
},
onAppReady: function () {
app.log("Ready");
},
onNotificationRegistered: function (msg) {
app.log("Registered: " + msg.registrationId);
},
onNotificationUnRegistered: function () {
app.log("UnRegistered");
},
onNotificationInline: function (data) {
app.log("Inline Notification: " + data);
},
onNotificationBackground: function (data) {
app.log("Background Notification: " + data);
},
onNotificationError: function (error) {
app.log("Error: " + error);
},
log: function (msg) {
console.log(msg);
},
};
Если вы хотите сохранить сообщения, вам просто нужно добавить свой код для хранения в sql, где сообщения получаются. Вам понадобится лазурная учетная запись, чтобы сделать эту работу, здесь вы можете получить бесплатный трейл. Это позволит вам бесплатно отправлять до 1 миллиона push-уведомлений в месяц бесплатно.
Ответ 3
Я думаю, что эта статья может быть полезной, она имеет больше непосредственного собственного обходного пути для вашего гибридного приложения для работы.
http://www.hiddentao.com/archives/2015/04/10/parse-push-notifications-for-your-android-and-ios-cordova-app/.
Я работаю над приложением Android от Кордовы, и это кажется рабочим решением