I am working on Push notifications for iPhone. I am sending notification on button click, but the iPhone developer is not receiving the alert message. Can anyone plz help me?
This is my method --
protected void btnPush_Click(object sender, EventArgs e)
{
string devicetoken = "bhsdse78 d52c6a34 273de5f7 27947945 24736e36 33d93a6c 3147a416 434995eb";
try
{
if (devicetoken != "")
{
//lblError.Visible = false;
string p12FileName = "D:/Worksapace/Coupzila/Certificates(3).p12"; // change this to reflect your own certificate
string p12Password = "seas"; // change this
bool sandBox = true;
int numConnections = 1; // you can change the number of connections here
var notificationService = new NotificationService(sandBox, p12FileName, p12Password, numConnections);
var deviceToken = devicetoken; // put in your device token here
var notification = new Notification(deviceToken);
notification.Payload.Alert.Body = "Hi this is push notification test message.";
notification.Payload.Sound = "default";
notification.Payload.Badge = 1;
notification.Payload.HideActionButton = true;
if (notificationService.QueueNotification(notification))
{ }
else
{ }
// This ensures any queued notifications get sent befor the connections are closed
notificationService.Close();
notificationService.Dispose();
}
else
{
//lblError.Visible = true;
}
}
catch (Exception ex)
{
}
}
This method is running successfully, but not getting notifications on iPhone, Whtz problem in my code?
Help me out, Thanks in advance
First, Remove the empty characters from your deviceToken.
Second, Put # sign for your fileName;
string p12FileName = #"D:/Worksapace/Coupzila/Certificates(3).p12";
And for the last step implement your catch, like;
catch (Exception ex)
{
MessageBox.Show("There is an error from push notification. Details:\n" + ex);
}
And good with Apple.
Related
We have an XF Forms app that we are adding subscription support for. We implemented Plugin.InAppBilling. Works as expected on iOS. We followed JM's docs for configuring on Android - but getting "This app not configured for subscriptions" error.
This is the purchase method we are using:
public async Task<InAppBillingPurchase> MakePurchase()
{
if (!CrossInAppBilling.IsSupported)
return null;
var currentPage = GetCurrentPage();
if(currentPage != null)
{
var confirm = await currentPage.DisplayAlert("Q5id subscription", "Become a subscriber to create an alert to find your loved one.","Confirm", "Cancel");
if (!confirm) return null;
}
var billing = CrossInAppBilling.Current;
try
{
var connected = await CrossInAppBilling.Current.ConnectAsync();
if (!connected)
{
//Couldn't connect to billing, could be offline, alert user
return null;
}
//try to purchase item
var purchase = await CrossInAppBilling.Current.PurchaseAsync(SUBSCRIPTION_PRODUCT_ID, ItemType.Subscription);
deviceService.DeviceLog("PurchaseAsync purchase: ", purchase);
var isFinish = await CrossInAppBilling.Current.FinishTransaction(purchase);
deviceService.DeviceLog("PurchaseAsync isFinish: ", isFinish);
return purchase;
}
catch (Exception ex)
{
Debug.WriteLine("Error MakePurchase: " + ex.Message);
deviceService.DeviceLog("Error MakePurchase: ", ex);
return null;
}
finally
{
await billing.DisconnectAsync();
}
}
We have verified bundleid, Play Console looks right. Any ideas?
I have a Xamarin.Forms application with a few renewable subscriptions. I am using the InAppBilling plugin to purchase these subscriptions. Now my questions is: (which I already asked in this post) How can I check if the renewable subscription is active? Thanks in advance.
Through the document, you can check the status by
var connected = await billing.ConnectAsync(ItemType.Subscription);:
Here is the example:
public async Task<bool> PurchaseItem(string productId, string payload)
{
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync(ItemType.InAppPurchase);
if (!connected)
{
//we are offline or can't connect, don't try to purchase
return false;
}
//check purchases
var purchase = await billing.PurchaseAsync(productId, ItemType.InAppPurchase, payload);
//possibility that a null came through.
if(purchase == null)
{
//did not purchase
}
else if(purchase.State == PurchaseState.Purchased)
{
//purchased!
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
//Billing Exception handle this based on the type
Debug.WriteLine("Error: " + purchaseEx);
}
catch (Exception ex)
{
//Something else has gone wrong, log it
Debug.WriteLine("Issue connecting: " + ex);
}
finally
{
await billing.DisconnectAsync();
}
I am using xamarin forms for app development. I am using firebase push notification for my app and using the following code for receiving notification. When my app is on foreground, the notification should not be swiped out, but when app is background we can swipe the notification. Please see the below code what i am using:
public override void OnMessageReceived(RemoteMessage message)
{
try
{
Android.Util.Log.Debug(TAG, "From: " + message.From);
Android.Util.Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
SendNotifications(message);
}
catch (System.Exception ex)
{
Logs.LogCreate("OnMessageReceived Exception" + ex.Message);
Crashes.TrackError(ex);
}
}
public void SendNotifications(RemoteMessage message)
{
try
{
NotificationManager manager = (NotificationManager)GetSystemService(NotificationService);
var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), #"\d+").Value);
int id = new Random(seed).Next(000000000, 999999999);
var push = new Intent();
var fullScreenPendingIntent = PendingIntent.GetActivity(this, 0,
push, PendingIntentFlags.CancelCurrent);
NotificationCompat.Builder notification;
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var chan1 = new NotificationChannel(PRIMARY_CHANNEL,
new Java.Lang.String("Primary"), NotificationImportance.High);
chan1.LightColor = Color.Green;
manager.CreateNotificationChannel(chan1);
notification = new NotificationCompat.Builder(this, PRIMARY_CHANNEL).SetOngoing(true);
}
else
{
notification = new NotificationCompat.Builder(this);
}
notification.SetContentIntent(fullScreenPendingIntent)
.SetContentTitle(message.GetNotification().Title)
.SetContentText(message.GetNotification().Body)
.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon))
.SetSmallIcon(Resource.Drawable.icon_transparent)
.SetStyle((new NotificationCompat.BigTextStyle()))
.SetPriority(NotificationCompat.PriorityHigh)
.SetColor(0x9c6114)
.SetAutoCancel(true)
.SetOngoing(true);
manager.Notify(id, notification.Build());
}
catch (System.Exception ex)
{
}
}
Please give me suggestions for this.
I receive correctly a notification from GCM but I want insert the message in a local (sqlite) database.
If I receive the notification when my app is not running, it doesn't insert the message but if my application was running then it does.
void SendNotification (string message)
{
var intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder (this)
.SetSmallIcon (Resource.Drawable.icstatbutton_click)
.SetContentTitle ("GCM Message")
.SetContentText ("U heeft een nieuwe vragenlijst.")
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify (0, notificationBuilder.Build());
try
{
DataAccess.InsertDownload (message);
}
catch (Exception ex)
{
}
}
Can I access sqlite database when my application is not running ?
Is your DataAccess.InsertDownload() method in your shared code? If so, that is the same thing I ran into.
Probably not the best way to solve it but what I did was to save the JSON string into Android's SharedPreferences if the app is in fact closed. Then the app is loaded again, within MainActivity and after loading the shared project, I attempt to read out any SharedPreferences and save them to the DB.
Below is some code showing this. Here is a link to SettingsImplementation.
public async Task SaveNotifToDb(Notification notification) {
try {
DataAccess.InsertDownload (message);
} catch(System.InvalidOperationException) { //InvalidOperationException is the exception given when your shared code is not yet loaded, meaning the app is closed, so now lets save to Preferences
System.Console.WriteLine("\nIn APP.Droid.Helpers.GcmService.SaveNotificationAsync() - InvalidOperationException, the app is probably closed. Saving to Shared Preferences\n");
string notificationJson = Newtonsoft.Json.JsonConvert.SerializeObject(notification);
string emptyCheck = SettingsImplementation.GetValueOrDefault<string>(DroidConstants.NotificationSettingKeyPart + "0", DroidConstants.NotificationSettingDefault);
if(emptyCheck.Length > 0) {
int index = 0;
while(emptyCheck.Length > 0) {
emptyCheck = SettingsImplementation.GetValueOrDefault<string>(DroidConstants.NotificationSettingKeyPart + index.ToString(), DroidConstants.NotificationSettingDefault);
index ++;
}
SettingsImplementation.AddOrUpdateValue<string>(DroidConstants.NotificationSettingKeyPart + (index - 1).ToString(), notificationJson);
} else { SettingsImplementation.AddOrUpdateValue<string>(DroidConstants.NotificationSettingKeyPart + "0", notificationJson); }
return notification;
}
}
Now when the app is started, we wait for the shared code to load and then try to read all the notification JSON back out.
MainActivity.OnCreate():
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
string notificationJson = SettingsImplementation.GetValueOrDefault(DroidConstants.NotificationSettingKeyPart + "0", DroidConstants.NotificationSettingDefault); //Check to see if we have a saved notification
if(notificationJson.Length > 0) {
int index = 0;
while(notificationJson.Length > 0) { //Keep trying until no more notifications can be gatherd
notificationJson = SettingsImplementation.GetValueOrDefault(DroidConstants.NotificationSettingKeyPart + index, DroidConstants.NotificationSettingDefault);
if(notificationJson.Length > 0) {
Data.Models.RemoteNotification notification = Newtonsoft.Json.JsonConvert.DeserializeObject<Data.Models.RemoteNotification>(notificationJson);
if(notification != null) {
try {
await App.RemoteNotificationRepo.InsertAsync(notification);
} catch(System.Exception e) {
System.Console.WriteLine("\nIn APP.Droid.MainActivity.OnCreate() - Exception attempting to create new in app notification\n{0}\n", e);
}
}
SettingsImplementation.Remove(DroidConstants.NotificationSettingKeyPart + index.ToString());
index++;
}
}
}
Yes. You can access Sqlite when application is not running. In your Activity's OnCreate you can check for new messages and update accordingly.
HI i have implemented push notification in my application, serer is sending notification but not receiving at my end.
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string typeString = String.Empty;
string notificationContent = String.Empty;
switch (e.NotificationType)
{
case PushNotificationType.Badge:
typeString = "Badge";
notificationContent = e.BadgeNotification.Content.GetXml();
break;
case PushNotificationType.Tile:
notificationContent = e.TileNotification.Content.GetXml();
typeString = "Tile";
break;
case PushNotificationType.Toast:
notificationContent = e.ToastNotification.Content.GetXml();
typeString = "Toast";
// Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts:
// if your application is already on the screen, there's no need to display a toast from push notifications.
e.Cancel = true;
break;
case PushNotificationType.Raw:
notificationContent = e.RawNotification.Content;
typeString = "Raw";
break;
}
// string text = "Received a " + typeString + " notification, containing: " + notificationContent;
var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// rootPage.NotifyUser(text, NotifyType.StatusMessage);
if (typeString == "Toast")
{
PushNotificationHelper.AddTostNotification(0, notificationContent);
}
else if (typeString == "Badge")
{
PushNotificationHelper.AddBadgeNotification(0, notificationContent);
}
});
}
public async void InitChannel()
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
try
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (channel != null)
{
//String existingChannel = (String)roamingSettings.Values["ExistingPushChannel"];
roamingSettings.Values["ExistingPushChannel"] = channel.Uri;
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
channel.PushNotificationReceived += OnPushNotificationReceived;
}
else
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
catch
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
public async void InitNotificationsAsync()
{
try
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
String existingChannel = (String)roamingSettings.Values["ExistingPushChannel"];
string tempDevelopmentKey = "";
string Platform = "";
List<string> arrayTags = new List<string>();
#if WINDOWS_APP
Platform = "windows-tablet";
tempDevelopmentKey = "dev_WindowsTabletNotification";
#endif
#if WINDOWS_PHONE_APP
Platform = "windows-phone";
tempDevelopmentKey ="dev_WindowsPhoneNotification";
#endif
arrayTags.Add(Platform) ;
arrayTags.Add(tempDevelopmentKey) ;
string TMBNotification = (string)roamingSettings.Values["TMBNotification"];
if(TMBNotification != null)
{
if(TMBNotification == "on")
{
arrayTags.Add("TMB");
}
}
string TRSNotification = (string)roamingSettings.Values["TRSNotification"];
if (TRSNotification != null)
{
if (TRSNotification == "on")
{
arrayTags.Add("TRS");
}
}
string IMNotification = (string)roamingSettings.Values["IMNotification"];
if (IMNotification != null)
{
if (IMNotification == "on")
{
arrayTags.Add("IM");
}
}
string SWSNotification = (string)roamingSettings.Values["SWSNotification"];
if (SWSNotification != null)
{
if (SWSNotification == "on")
{
arrayTags.Add("ANC");
}
}
string VIDNotification = (string)roamingSettings.Values["VIDNotification"];
if (VIDNotification != null)
{
if (VIDNotification == "on")
{
arrayTags.Add("videos");
}
}
var hub = new NotificationHub("hubname", "endpoint");
var result = await hub.RegisterNativeAsync(existingChannel, arrayTags);
// Displays the registration ID so you know it was successful
if (result.RegistrationId != null)
{
}
}catch
{
}
}
So how can i confirm that there is no issue in my implementation or there is issue from server end.
There are couple of steps you can take to debug this problem:-
There is broadcast and sending notification, using notification hub, option available on azure portal(you can do from VS also from left side server explorer). When you did this there is a log that will show you whether a notifications sent successfully or not.
First just delete all your registrations with notification hub and for very new registration check is your device getting registered with correct tags/channel uri or not(this you cad do from server explorer too)
Make sure you are sending/registering the correct templates that are corresponding to WNS service.
make sure you are using WNS service this different from what is for
WP8 silverlight one.
You can see the errors just at the bottom of this page if any.
There is option for device registrations from where you can alter the registrations.