Skip to content

Instantly share code, notes, and snippets.

@astjohn
Created October 4, 2017 15:09
Show Gist options
  • Save astjohn/1c8cdca7f9b937f63cd2f1fea3aa941b to your computer and use it in GitHub Desktop.
Save astjohn/1c8cdca7f9b937f63cd2f1fea3aa941b to your computer and use it in GitHub Desktop.
xamarin setup with push notifications
using Foundation;
using SitataCore;
using UIKit;
using UserNotifications;
namespace SitataQs
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window
{
get;
set;
}
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// Override point for customization after application launch.
// If not required for your application you can safely delete this method
NSString token = (NSString) "TKN UGFydG5lcjo6RXh0ZXJuYWxUcmF2ZWxsZXJ8NTkxOTAzNDNiODdkOTEyYzg3NTBlNTQ2fHRDeS00WXNfLW94ZFZ5S3VNNjE4";
NSString endpoint = (NSString) "https://staging.sitata.com";
var ctrl = STASDKController.SharedInstance;
ctrl.SetConfig(token, endpoint);
// NOTE: You need to send the device token to Sitata after you know who the traveller is
// i.e. after ctrl.SetConfig.
// If you are calling ctrl.SetConfig elsewhere, and you know you haven't sent the
// traveller token to Sitata yet, then you should keep track of the device token (as shown below)
// and pull it out so you can send it to Sitata.
SendDeviceTokenToServers();
ctrl.SkipTBTypes = true;
ctrl.SkipTBActivities = true;
ctrl.FixedTripDates = true;
var styles = STASDKUIStylesheet.SharedInstance;
styles.HeadingTextColor = UIColor.Red;
styles.SubheadingTextColor = UIColor.Blue;
styles.BodyTextColor = UIColor.Yellow;
styles.TitleTextColor = UIColor.Purple;
styles.HeadingFont = UIFont.SystemFontOfSize(24, 100);
styles.SubHeadingFont = UIFont.SystemFontOfSize(18, 50);
styles.BodyFont = UIFont.SystemFontOfSize(10, 5);
styles.TitleFont = UIFont.SystemFontOfSize(12, 4);
styles.NavigationBarFont = UIFont.SystemFontOfSize(10, 1);
// STASDKUIStylesheet *styles = [STASDKUIStylesheet sharedInstance];
styles.ButtonFont = UIFont.ItalicSystemFontOfSize(14);
styles.AlertsRowNormalFont = UIFont.SystemFontOfSize(13);
styles.AlertsRowUnreadFont = UIFont.ItalicSystemFontOfSize(13);
styles.HospitalAccredationLblFont = UIFont.ItalicSystemFontOfSize(12);
styles.HospitalEmergencyLblFont = UIFont.ItalicSystemFontOfSize(12);
styles.HospitalAccredationLblColor = UIColor.Green;
styles.HospitalEmergencyLblColor = UIColor.Orange;
styles.HospitalContactNoteLblColor = UIColor.Brown;
if (launchOptions != null && launchOptions[UIApplication.LaunchOptionsRemoteNotificationKey] != null)
{
// re-using remote notification logic here for when app loads after user
// has interacted with remote notification from tray
this.DidReceiveRemoteNotification(application, launchOptions, (UIBackgroundFetchResult result) =>
{
// do nothing after handled
});
}
// Register for push notifications - ideally, you would want to do this after explaining to the
// user why you're requesting them.
application.ApplicationIconBadgeNumber = 0;
System.Version v = new System.Version(UIDevice.CurrentDevice.SystemVersion);
if (v.Major < 10) {
// iOS 10.0 and below (Sitata SDK supports 9.0 and above).
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
} else {
// iOS 10.0 and above
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
center.Delegate = new UserNotificationCenterDelegate(); // see below
UNAuthorizationOptions options = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
center.RequestAuthorization(options, (granted, error) =>
{
InvokeOnMainThread(() =>
{
System.Console.WriteLine("DID FINISH REQUEST SUCCESS");
if (error == null)
{
System.Console.WriteLine("REQUEST SUCCESS");
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
// request failed.
}
});
});
}
return true;
}
public override void OnResignActivation(UIApplication application)
{
// Invoked when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Games should use this method to pause the game.
STASDKController.SharedInstance.Stop();
}
public override void DidEnterBackground(UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
}
public override void WillEnterForeground(UIApplication application)
{
// Called as part of the transiton from background to active state.
// Here you can undo many of the changes made on entering the background.
}
public override void OnActivated(UIApplication application)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
STASDKController.SharedInstance.Start();
}
public override void WillTerminate(UIApplication application)
{
// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
}
// == NOTIFICATIONS == //
public override void DidRegisterUserNotificationSettings(UIApplication application, UIUserNotificationSettings notificationSettings)
{
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
var DeviceToken = deviceToken.Description;
if (!string.IsNullOrWhiteSpace(DeviceToken))
{
DeviceToken = DeviceToken.Trim('<').Trim('>');
if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
{
// we have an old token so we should store it and send it to our servers
NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
NSUserDefaults.StandardUserDefaults.SetBool(false, "tokenSentToSitata");
NSUserDefaults.StandardUserDefaults.SetBool(false, "tokenSentToTII");
SendDeviceTokenToServers();
}
}
}
// Send token to servers
public void SendDeviceTokenToServers() {
var deviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
if (!NSUserDefaults.StandardUserDefaults.BoolForKey("tokenSentToTII")) {
// TODO: Send to TII SERVERS?
// on success:
// NSUserDefaults.StandardUserDefaults.SetBool(true, "tokenSentToSitata");
}
// Send token to stiata
if (!NSUserDefaults.StandardUserDefaults.BoolForKey("tokenSentToSitata")) {
var sitataCtrl = STASDKController.SharedInstance;
sitataCtrl.SetPushNotificationToken(deviceToken);
NSUserDefaults.StandardUserDefaults.SetBool(true, "tokenSentToSitata");
}
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, System.Action<UIBackgroundFetchResult> completionHandler)
{
base.DidReceiveRemoteNotification(application, userInfo, completionHandler);
var sitataCtrl = STASDKController.SharedInstance;
sitataCtrl.ReceivePushNotification(userInfo, completionHandler);
if (application.ApplicationState == UIApplicationState.Active)
{
// app is currently active, can update badges or visuals here
}
else if (application.ApplicationState == UIApplicationState.Background)
{
// app is in background
}
else if (application.ApplicationState == UIApplicationState.Inactive)
{
// app is transitioning from background to foreground (user taps notification)
// launch the screen for a particular push notification (when applicable)
sitataCtrl.LaunchPushNotificationScreen(userInfo);
}
}
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate {
public UserNotificationCenterDelegate() {
}
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler)
{
System.Console.WriteLine("UserNotificationCenterDelegate: WILL PRESENT NOTIFICATION.");
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler(UNNotificationPresentationOptions.Alert);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment