Skip to content

Instantly share code, notes, and snippets.

@miguelangelgonzalez
Created January 11, 2018 18:11
Show Gist options
  • Save miguelangelgonzalez/bb658e121b5c7a90be14e8e455ad5058 to your computer and use it in GitHub Desktop.
Save miguelangelgonzalez/bb658e121b5c7a90be14e8e455ad5058 to your computer and use it in GitHub Desktop.
Example of push shrap sending an alert to IOS
using System;
using Newtonsoft.Json.Linq;
using PushSharp.Apple;
namespace DeploymentUnit
{
class Program
{
static void Main(string[] args)
{
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, "PushCertificate.p12", "MoniesDev911!");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine("Apple Notification Sent!");
};
// Start the broker
apnsBroker.Start();
Random r = new Random();
int rInt = r.Next(0, 100);
foreach (var deviceToken in new []{ "8F88C1A09E65058B1CC0AFABEB82EDB215DD37AEA79802F788626693A62DF8D6" })
{
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse("{\"aps\":{\"badge\":2, \"alert\" : \"Test send random #" + rInt + " \"}}")
});
}
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string deviceToken, DateTime timestamp) => {
Console.WriteLine("Removeing an expired APN deviceToken");
// Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
};
fbs.Check();
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment