예제 #1
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            InstantiateStoryboards();
            InstantiateUserDefaults();
            _data.IncrementRatingCycle();

            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound, (approved, err) =>
            {
                UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();
            });

            var nextAction     = UNNotificationAction.FromIdentifier(Constants.NextId, "Change", UNNotificationActionOptions.None);
            var completeAction = UNNotificationAction.FromIdentifier(Constants.CompleteId, "Complete", UNNotificationActionOptions.None);

            var actions   = new[] { nextAction, completeAction };
            var intentIDs = new string[] { };

            var category = UNNotificationCategory.FromIdentifier(Constants.ExerciseNotificationCategoryId, actions, intentIDs, UNNotificationCategoryOptions.CustomDismissAction);

            var categories = new[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

            UINavigationBar.Appearance.BarTintColor        = Colors.PrimaryColor;
            UINavigationBar.Appearance.Translucent         = false;
            UINavigationBar.Appearance.TitleTextAttributes = new UIStringAttributes
            {
                ForegroundColor = UIColor.White
            };

            return(true);
        }
예제 #2
0
        void RegisterForNotifications()
        {
            // Create action
            var actionID = "check";
            var title    = "Check";
            var action   = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.Foreground);

            // Create category
            categoryID = "notification";
            var actions   = new UNNotificationAction[] { };
            var intentIDs = new string[] { };
            //var categoryOptions = new UNNotificationCategoryOptions[] { };
            var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            // Register category
            var categories = new UNNotificationCategory[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                                                                  (a, err) =>
            {
                //TODO handle error
            });
        }
        public NotificationService(IPermissionsService permissionsService, ITimeService timeService)
            : base(permissionsService)
        {
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));

            this.timeService = timeService;

            var openAndCreateFromCalendarEventAction = UNNotificationAction.FromIdentifier(
                OpenAndCreateFromCalendarEvent,
                FoundationResources.OpenAppAndStartAction,
                UNNotificationActionOptions.AuthenticationRequired | UNNotificationActionOptions.Foreground
                );

            var openAndNavigateToCalendarAction = UNNotificationAction.FromIdentifier(
                OpenAndNavigateToCalendar,
                FoundationResources.OpenAppAction,
                UNNotificationActionOptions.AuthenticationRequired | UNNotificationActionOptions.Foreground
                );

            var startTimeEntryInBackgroundAction = UNNotificationAction.FromIdentifier(
                StartTimeEntryInBackground,
                FoundationResources.StartInBackgroundAction,
                UNNotificationActionOptions.AuthenticationRequired
                );

            var calendarEventCategory = UNNotificationCategory.FromIdentifier(
                CalendarEventCategory,
                new UNNotificationAction[] { openAndCreateFromCalendarEventAction, startTimeEntryInBackgroundAction, openAndNavigateToCalendarAction },
                new string[] { },
                UNNotificationCategoryOptions.None
                );

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(calendarEventCategory));
        }
예제 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        protected static UNNotificationCategory RegisterActionList(NotificationCategory category)
        {
            if (category is null || category.CategoryType == NotificationCategoryType.None)
            {
                return(null);
            }

            var nativeActionList = new List <UNNotificationAction>();

            foreach (var notificationAction in category.ActionList)
            {
                if (notificationAction.ActionId == -1000)
                {
                    continue;
                }

                var nativeAction = UNNotificationAction.FromIdentifier(notificationAction.ActionId.ToString(CultureInfo.InvariantCulture), notificationAction.Title,
                                                                       ToNativeActionType(notificationAction.iOSAction));
                nativeActionList.Add(nativeAction);
            }

            if (nativeActionList.Any() == false)
            {
                return(null);
            }

            var notificationCategory = UNNotificationCategory
                                       .FromIdentifier(ToNativeCategory(category.CategoryType), nativeActionList.ToArray(), Array.Empty <string>(), UNNotificationCategoryOptions.CustomDismissAction);

            return(notificationCategory);
        }
예제 #5
0
        static void RegisterUserNotificationCategories(NotificationUserCategory[] userCategories)
        {
            if (userCategories != null && userCategories.Length > 0)
            {
                usernNotificationCategories.Clear();
                IList <UNNotificationCategory> categories = new List <UNNotificationCategory>();
                foreach (var userCat in userCategories)
                {
                    IList <UNNotificationAction> actions = new List <UNNotificationAction>();

                    foreach (var action in userCat.Actions)
                    {
                        // Create action
                        var actionID = action.Id;
                        var title    = action.Title;
                        var notificationActionType = UNNotificationActionOptions.None;
                        switch (action.Type)
                        {
                        case NotificationActionType.AuthenticationRequired:
                            notificationActionType = UNNotificationActionOptions.AuthenticationRequired;
                            break;

                        case NotificationActionType.Destructive:
                            notificationActionType = UNNotificationActionOptions.Destructive;
                            break;

                        case NotificationActionType.Foreground:
                            notificationActionType = UNNotificationActionOptions.Foreground;
                            break;
                        }


                        var notificationAction =
                            UNNotificationAction.FromIdentifier(actionID, title, notificationActionType);

                        actions.Add(notificationAction);
                    }

                    // Create category
                    var categoryID          = userCat.Category;
                    var notificationActions = actions.ToArray() ?? new UNNotificationAction[] { };
                    var intentIDs           = new string[] { };
                    var categoryOptions     = new UNNotificationCategoryOptions[] { };

                    var category = UNNotificationCategory.FromIdentifier(categoryID, notificationActions, intentIDs,
                                                                         userCat.Type == NotificationCategoryType.Dismiss
                            ? UNNotificationCategoryOptions.CustomDismissAction
                            : UNNotificationCategoryOptions.None);

                    categories.Add(category);

                    usernNotificationCategories.Add(userCat);
                }

                // Register categories
                UNUserNotificationCenter.Current.SetNotificationCategories(
                    new NSSet <UNNotificationCategory>(categories.ToArray()));
            }
        }
예제 #6
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            Dictionary <string, object> dict = (Dictionary <string, object>)PListCSLight.readPlist("Info.plist");

            Profile.EnableUpdatesOnAccessTokenChange(true);
            Facebook.CoreKit.Settings.AppID       = dict.GetValueOrDefault("FacebookAppID").ToString();
            Facebook.CoreKit.Settings.DisplayName = dict.GetValueOrDefault("FacebookDisplayName").ToString();

            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            ApplicationDelegate.SharedInstance.FinishedLaunching(app, options);


            var settings = UIUserNotificationSettings.GetSettingsForTypes(
                UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                new NSSet());

            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();


            //Create accept action
            var replyId     = "reply";
            var replyTitle  = "Reply";
            var replyAction = UNTextInputNotificationAction.FromIdentifier(replyId, replyTitle, UNNotificationActionOptions.None, "Reply", "Message");



            //Create category
            var categoryID      = "general";
            var actions         = new UNNotificationAction[] { replyAction };
            var intentIDs       = new string[] { };
            var categoryOptions = new UNNotificationCategoryOptions[] { };
            var category        = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            //Register category
            var categories = new UNNotificationCategory[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));



            UNUserNotificationCenter.Current.Delegate = new CustomUNUserNotificationCenterDelegate();


            if (options != null && options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
            {
                appIsStarting = true;
            }

            return(base.FinishedLaunching(app, options));
        }
        public void whenCanUShare()
        {
            // Create action
            var actionID = "ten";
            var title    = "10 minutes";
            var action   = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.Foreground);

            var actionID2 = "fifteen";
            var title2    = "15 minutes";
            var action2   = UNNotificationAction.FromIdentifier(actionID2, title2, UNNotificationActionOptions.None);

            var actionID3 = "thirty";
            var title3    = "30 minutes";
            var action3   = UNNotificationAction.FromIdentifier(actionID3, title3, UNNotificationActionOptions.None);

            var actionID4 = "leave";
            var title4    = "When I leave";
            var action4   = UNNotificationAction.FromIdentifier(actionID4, title4, UNNotificationActionOptions.None);

            // Create category
            var categoryID      = "remindlater";
            var actions         = new UNNotificationAction[] { action, action2, action3, action4 };
            var intentIDs       = new string[] { };
            var categoryOptions = new UNNotificationCategoryOptions[] { };
            var category        = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            // Register category
            var categories = new UNNotificationCategory[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

            var content = new UNMutableNotificationContent();

            content.Title              = "Scuttle";
            content.Subtitle           = " ";
            content.Body               = "When can you share?";
            content.Badge              = 1;
            content.CategoryIdentifier = "remindlater";

            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(2, false);

            var requestID = "sampleRequest";
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    // Do something with error...
                }
            });
        }
예제 #8
0
 private void SaveAction(string categoryId, UNNotificationAction action)
 {
     if (_actionsForCategories.ContainsKey(categoryId))
     {
         _actionsForCategories[categoryId].Add(action);
     }
     else
     {
         _actionsForCategories.Add(categoryId, new List <UNNotificationAction> {
             action
         });
     }
 }
예제 #9
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // Set log level for debugging config loading (optional)
            // It will be set to the value in the loaded config upon takeOff
            UAirship.LogLevel = UALogLevel.Trace;

            // Populate AirshipConfig.plist with your app's info from https://go.urbanairship.com
            // or set runtime properties here.
            UAConfig config = UAConfig.DefaultConfig();

            if (!config.Validate())
            {
                throw new RuntimeException("The AirshipConfig.plist must be a part of the app bundle and " +
                                           "include a valid appkey and secret for the selected production level.");
            }

            WarnIfSimulator();

            // Bootstrap the Airship SDK
            UAirship.TakeOff(config, options);

            Console.WriteLine("Config:{0}", config);

            UAirship.Push.ResetBadge();

            pushHandler = new PushHandler();
            UAirship.Push.PushNotificationDelegate = pushHandler;

            UNNotificationAction sampleAction = UNNotificationAction.FromIdentifier("sampleAction", title: "Sample Action Title", options: UNNotificationActionOptions.Destructive);

            var sampleActions     = new UNNotificationAction[] { sampleAction };
            var intentIdentifiers = new string[] { };

            // Create category for sample content extension
            UNNotificationCategory[]       SampleCategoryArray = { UNNotificationCategory.FromIdentifier("sample-extension-category", actions: sampleActions, intentIdentifiers: intentIdentifiers, options: UNNotificationCategoryOptions.None) };
            NSSet <UNNotificationCategory> categories          = new NSSet <UNNotificationCategory>(SampleCategoryArray);

            // Add sample content extension category to Airship custom categories
            UAirship.Push.CustomCategories = categories;

            UAirship.Push.WeakRegistrationDelegate = this;

            NSNotificationCenter.DefaultCenter.AddObserver(new NSString("channelIDUpdated"), (notification) =>
            {
                //FIXME: Find a way to call the refreshView from the HomeViewController
            });

            InitFormsApp();

            return(base.FinishedLaunching(app, options));
        }
예제 #10
0
        private void CreateNotificationCustomActions(UNMutableNotificationContent content)
        {
            var categoryIdentifier    = "foodpin.restaurantaction";
            var makeReservationAction = UNNotificationAction.FromIdentifier("foodpin.makeReservation", "Reserve a table", UNNotificationActionOptions.Foreground);
            var cancelAction          = UNNotificationAction.FromIdentifier("foodpin.cancel", "Later", UNNotificationActionOptions.None);

            UNNotificationAction[] actions = new UNNotificationAction[] { makeReservationAction, cancelAction };
            string[] intentIdentifiers     = new string[] { };
            UNNotificationCategoryOptions notificationCategoryOptions = new UNNotificationCategoryOptions();
            var category = UNNotificationCategory.FromIdentifier(categoryIdentifier, actions, intentIdentifiers, notificationCategoryOptions);

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(category));
            content.CategoryIdentifier = categoryIdentifier;
        }
예제 #11
0
        partial void CustomActionTapped(Foundation.NSObject sender)
        {
            // Create action
            var actionID = "reply";
            var title    = "Reply";
            var action   = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);

            // Create category
            var categoryID = "message";
            var actions    = new UNNotificationAction[] { action };
            var intentIDs  = new string[] { };
            //var categoryOptions = new UNNotificationCategoryOptions[] { };
            var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            // Register category
            var categories = new UNNotificationCategory[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

            // Create content
            var content = new UNMutableNotificationContent();

            content.Title              = "Custom Action";
            content.Subtitle           = "Notification Subtitle";
            content.Body               = "This is the message body of the notification.";
            content.Badge              = 1;
            content.CategoryIdentifier = "message";

            // Fire trigger in twenty seconds
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(20, false);

            var requestID = "sampleRequest";
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    // Report error
                    Console.WriteLine("Error: {0}", err);
                }
                else
                {
                    // Report Success
                    Console.WriteLine("Notification Scheduled: {0}", request);
                }
            });
        }
        public void Register()
        {
            var actions = RegisteredActions
                          .OfType <ButtonLocalNotificationActionRegistration>()
                          .Select(action => UNNotificationAction.FromIdentifier(action.Id, action.Title, UNNotificationActionOptions.None))
                          .ToArray();

            var category = UNNotificationCategory.FromIdentifier(
                ActionSetId,
                actions,
                new string[] { },
                UNNotificationCategoryOptions.CustomDismissAction);

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(category));
            LocalNotifications.Initialize();
        }
예제 #13
0
        private void RegisterCategoriesNotification()
        {
            var commentID            = "comment";
            var commentTitle         = "Comment";
            var textInputButtonTitle = "Send";
            var textInputPlaceholder = "Enter comment here...";
            var commentAction        = UNTextInputNotificationAction.FromIdentifier(commentID, commentTitle, UNNotificationActionOptions.None, textInputButtonTitle, textInputPlaceholder);

            // Create category
            var categoryID = "event-invite";
            var actions    = new UNNotificationAction[] { acceptAction, declineAction, commentAction };
            var intentIDs  = new string[] { };
            // actions can be construted by UNTextInputNotificationAction class if you want to actions to that
            // perticular category
            var sampleCategory = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(new UNNotificationCategory[] { sampleCategory }));
        }
예제 #14
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            var settings = UIUserNotificationSettings.GetSettingsForTypes(
                UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                new NSSet());

            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();


            //Create accept action
            var replyId     = "reply";
            var replyTitle  = "Reply";
            var replyAction = UNTextInputNotificationAction.FromIdentifier(replyId, replyTitle, UNNotificationActionOptions.None, "Reply", "Message");



            //Create category
            var categoryID      = "general";
            var actions         = new UNNotificationAction[] { replyAction };
            var intentIDs       = new string[] { };
            var categoryOptions = new UNNotificationCategoryOptions[] { };
            var category        = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            //Register category
            var categories = new UNNotificationCategory[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));



            UNUserNotificationCenter.Current.Delegate = new CustomUNUserNotificationCenterDelegate();


            if (options != null && options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
            {
                appIsStarting = true;
            }

            return(base.FinishedLaunching(app, options));
        }
        public static void CreateAction_Category()
        {
            var Actions  = new List <UNNotificationAction>();
            var actionID = string.Empty;
            var title    = string.Empty;

            var actionID1 = "reply";
            var title1    = "Reply";

            var actionID2 = "test";
            var title2    = "Test";

            var textInputButtonTitle = "GO";
            var textInputPlaceholder = "Enter comment here...";

            for (int i = 0; i < 2; i++)
            {
                if (i == 0)
                {
                    actionID = actionID1;
                    title    = title1;
                    var action_input = UNTextInputNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None, textInputButtonTitle, textInputPlaceholder);
                    Actions.Add(action_input);
                }
                else
                {
                    actionID = actionID2;
                    title    = title2;
                    var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);
                    Actions.Add(action);
                }
            }

            // Create category
            var categoryID = "message";
            var actions    = Actions.ToArray();
            var intentIDs  = new string[] { };
            var category   = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

            // Register category
            var categories = new UNNotificationCategory[] { category };

            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));
        }
예제 #16
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Request authorization to send notifications
            UNUserNotificationCenter center = UNUserNotificationCenter.Current;
            var options = UNAuthorizationOptions.ProvidesAppNotificationSettings | UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Provisional;

            center.RequestAuthorization(options, (bool success, NSError error) =>
            {
                center.Delegate = this;

                var rotateTwentyDegreesAction = UNNotificationAction.FromIdentifier("rotate-twenty-degrees-action", "Rotate 20°", UNNotificationActionOptions.None);

                var redCategory = UNNotificationCategory.FromIdentifier(
                    "red-category",
                    new UNNotificationAction[] { rotateTwentyDegreesAction },
                    new string[] { },
                    UNNotificationCategoryOptions.CustomDismissAction
                    );

                var greenCategory = UNNotificationCategory.FromIdentifier(
                    "green-category",
                    new UNNotificationAction[] { rotateTwentyDegreesAction },
                    new string[] { },
                    UNNotificationCategoryOptions.CustomDismissAction
                    );

                var set = new NSSet <UNNotificationCategory>(redCategory, greenCategory);
                center.SetNotificationCategories(set);
            });

            // Initialize granular notification settings on first run
            bool initializedNotificationSettings = NSUserDefaults.StandardUserDefaults.BoolForKey(InitializedNotificationSettingsKey);

            if (!initializedNotificationSettings)
            {
                NSUserDefaults.StandardUserDefaults.SetBool(true, ManageNotificationsViewController.RedNotificationsEnabledKey);
                NSUserDefaults.StandardUserDefaults.SetBool(true, ManageNotificationsViewController.GreenNotificationsEnabledKey);
                NSUserDefaults.StandardUserDefaults.SetBool(true, InitializedNotificationSettingsKey);
            }
            return(true);
        }
        public void DidReceiveNotificationResponse(UNNotificationResponse response, Action <UNNotificationContentExtensionResponseOption> completionHandler)
        {
            var rotationAction = ExtensionContext.GetNotificationActions()[0];

            if (response.ActionIdentifier == "rotate-twenty-degrees-action")
            {
                rotationButtonTaps += 1;

                double radians = (20 * rotationButtonTaps) * (2 * Math.PI / 360.0);
                Xamagon.Transform = CGAffineTransform.MakeRotation((float)radians);

                // 9 rotations * 20 degrees = 180 degrees. No reason to
                // show the reset rotation button when the image is half
                // or fully rotated.
                if (rotationButtonTaps % 9 == 0)
                {
                    ExtensionContext.SetNotificationActions(new UNNotificationAction[] { rotationAction });
                }
                else if (rotationButtonTaps % 9 == 1)
                {
                    var resetRotationAction = UNNotificationAction.FromIdentifier("reset-rotation-action", "Reset rotation", UNNotificationActionOptions.None);
                    ExtensionContext.SetNotificationActions(new UNNotificationAction[] { rotationAction, resetRotationAction });
                }
            }

            if (response.ActionIdentifier == "reset-rotation-action")
            {
                rotationButtonTaps = 0;

                double radians = (20 * rotationButtonTaps) * (2 * Math.PI / 360.0);
                Xamagon.Transform = CGAffineTransform.MakeRotation((float)radians);

                ExtensionContext.SetNotificationActions(new UNNotificationAction[] { rotationAction });
            }

            completionHandler(UNNotificationContentExtensionResponseOption.DoNotDismiss);
        }
예제 #18
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();

            // Code for starting up the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
            Xamarin.Calabash.Start();
#endif

            LoadApplication(new App());


            // Handling Push notification when app is closed if App was opened by Push Notification...
            if (options != null && options.Keys != null && options.Keys.Count() != 0 && options.ContainsKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")))
            {
                NSDictionary UIApplicationLaunchOptionsRemoteNotificationKey = options.ObjectForKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")) as NSDictionary;

                ProcessNotification(UIApplicationLaunchOptionsRemoteNotificationKey, true);
            }

            //added on 1/7/17 by aditmer to see if the device token from APNS has changed (like after an app update)
            if (ApplicationSettings.InstallationID != "")
            {
                //Push notifications registration
                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                        UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                        new NSSet());

                    UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                }
                else
                {
                    UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                    UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
                }
            }
            //added on 1/4/17 by aditmer to add 4 (1/6/17) customizable snooze options
            int snoozeTime1 = 1;
            int snoozeTime2 = 2;
            int snoozeTime3 = 3;
            int snoozeTime4 = 4;

            if (ApplicationSettings.AlarmUrgentLowMins1 != 0)
            {
                snoozeTime1 = ApplicationSettings.AlarmUrgentLowMins1;
            }

            if (ApplicationSettings.AlarmUrgentLowMins2 != 0)
            {
                snoozeTime2 = ApplicationSettings.AlarmUrgentLowMins2;
            }

            if (ApplicationSettings.AlarmUrgentMins1 != 0)
            {
                snoozeTime3 = ApplicationSettings.AlarmUrgentMins1;
            }

            if (ApplicationSettings.AlarmUrgentMins2 != 0)
            {
                snoozeTime4 = ApplicationSettings.AlarmUrgentMins2;
            }


            //added on 12/03/16 by aditmer to add custom actions to the notifications (I think this code goes here)
            // Create action
            var actionID = "snooze1";
            var title    = $"Snooze {snoozeTime1} minutes";
            var action   = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);

            var actionID2 = "snooze2";
            var title2    = $"Snooze {snoozeTime2} minutes";
            var action2   = UNNotificationAction.FromIdentifier(actionID2, title2, UNNotificationActionOptions.None);

            var actionID3 = "snooze3";
            var title3    = $"Snooze {snoozeTime3} minutes";
            var action3   = UNNotificationAction.FromIdentifier(actionID3, title3, UNNotificationActionOptions.None);

            var actionID4 = "snooze4";
            var title4    = $"Snooze {snoozeTime4} minutes";
            var action4   = UNNotificationAction.FromIdentifier(actionID4, title4, UNNotificationActionOptions.None);

            // Create category
            var categoryID = "event";
            var actions    = new List <UNNotificationAction> {
                action, action2, action3, action4
            };
            var intentIDs       = new string[] { };
            var categoryOptions = new UNNotificationCategoryOptions[] { };

            //added on 1/19/17 by aditmer to remove duplicate snooze options (they can be custom set by each user in their Nightscout settings)
            actions = actions.DistinctBy((arg) => arg.Title).ToList();


            var category = UNNotificationCategory.FromIdentifier(categoryID, actions.ToArray(), intentIDs, UNNotificationCategoryOptions.AllowInCarPlay);

            // Register category
            var categories = new UNNotificationCategory[] { category };
            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

            return(base.FinishedLaunching(app, options));
        }
예제 #19
0
        private async Task <UNMutableNotificationContent> EnrichNotificationContentAsync(UNMutableNotificationContent content, NotificationDto notification)
        {
            if (!string.IsNullOrWhiteSpace(notification.Subject))
            {
                content.Title = notification.Subject;
            }

            if (!string.IsNullOrWhiteSpace(notification.Body))
            {
                content.Body = notification.Body;
            }

            string image = string.IsNullOrWhiteSpace(notification.ImageLarge) ? notification.ImageSmall : notification.ImageLarge;

            if (!string.IsNullOrWhiteSpace(image))
            {
                var imagePath = await GetImageAsync(image);

                if (!string.IsNullOrWhiteSpace(imagePath))
                {
                    var uniqueName     = $"{Guid.NewGuid()}{Path.GetExtension(imagePath)}";
                    var attachementUrl = new NSUrl(uniqueName, NSFileManager.DefaultManager.GetTemporaryDirectory());

                    NSFileManager.DefaultManager.Copy(NSUrl.FromFilename(imagePath), attachementUrl, out var error);
                    if (error != null)
                    {
                        Log.Error(error.LocalizedDescription);
                    }

                    var attachement = UNNotificationAttachment.FromIdentifier(
                        Constants.ImageLargeKey,
                        attachementUrl,
                        new UNNotificationAttachmentOptions(),
                        out error);

                    if (error == null)
                    {
                        content.Attachments = new UNNotificationAttachment[] { attachement };
                    }
                    else
                    {
                        Log.Error(error.LocalizedDescription);
                    }
                }
            }

            var actions = new List <UNNotificationAction>();

            if (!string.IsNullOrWhiteSpace(notification.ConfirmUrl) &&
                !string.IsNullOrWhiteSpace(notification.ConfirmText) &&
                !notification.IsConfirmed)
            {
                var confirmAction = UNNotificationAction.FromIdentifier(
                    Constants.ConfirmAction,
                    notification.ConfirmText,
                    UNNotificationActionOptions.Foreground);

                actions.Add(confirmAction);
            }

            if (!string.IsNullOrWhiteSpace(notification.LinkUrl) &&
                !string.IsNullOrWhiteSpace(notification.LinkText))
            {
                var linkAction = UNNotificationAction.FromIdentifier(
                    Constants.LinkAction,
                    notification.LinkText,
                    UNNotificationActionOptions.Foreground);

                actions.Add(linkAction);
            }

            if (actions.Any())
            {
                var categoryId = Guid.NewGuid().ToString();

                var newCategory = UNNotificationCategory.FromIdentifier(
                    categoryId,
                    actions.ToArray(),
                    new string[] { },
                    UNNotificationCategoryOptions.None);

                var categories = new List <UNNotificationCategory>();

                var allCategories = await UNUserNotificationCenter.Current.GetNotificationCategoriesAsync();

                if (allCategories != null)
                {
                    foreach (UNNotificationCategory category in allCategories)
                    {
                        if (category.Identifier != categoryId)
                        {
                            categories.Add(category);
                        }
                    }

                    categories.Add(newCategory);
                }
                else
                {
                    categories.Add(newCategory);
                }

                UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories.ToArray()));

                // without this call action buttons won't be added or updated
                _ = await UNUserNotificationCenter.Current.GetNotificationCategoriesAsync();

                content.CategoryIdentifier = categoryId;
            }

            if (content.Sound == null)
            {
                content.Sound = UNNotificationSound.Default;
            }

            notificationHandler?.OnBuildNotification(content, notification);

            return(content);
        }
예제 #20
0
        /// <summary>
        ///     A method to create and save an Action for a specific Category Id. See UNNotificationAction.FromIdentifier.
        /// </summary>
        /// <remarks>
        ///     Should be called before AddCategory for this Category Id in order to have action attached to the category.
        /// </remarks>
        /// <param name="categoryId">Identifier for the Category connected with this Action.</param>
        /// <param name="actionId">
        ///     The string that you use internally to identify the Action.
        ///     This string must be unique among all of your app's supported Actions.
        /// </param>
        /// <param name="title">Localized string that will be displayed on Action button (probably localized).</param>
        /// <param name="options">Additional options describing how the Action behaves.</param>
        protected void AddAction(string categoryId, string actionId, string title, UNNotificationActionOptions options)
        {
            var action = UNNotificationAction.FromIdentifier(actionId, title, options);

            SaveAction(categoryId, action);
        }
        //public UserNotificationDelegate()
        //{
        //var content = new UNMutableNotificationContent();
        //content.Title = "Scuttle";
        //content.Subtitle = " ";
        //content.Body = "Hey! Are you at "+App.RestoName;
        //content.Badge = 1;

        //var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);

        //var requestID = "sampleRequest";
        //var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

        //UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
        //{
        //    if (err != null)
        //    {
        //        // Do something with error...
        //    }
        //});

        //WillPresentNotification(UNUserNotificationCenter.Current, content, (UNNotificationPresentationOptions obj) =>
        //{

        //});
        //}
        #region ask if the user is in a restaurant
        public void sendLocalNotif(string name)
        {
            if (name.Equals("reminder"))
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    //var actionID = "yes2";
                    //var title = "Yes";
                    //var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);

                    //var actionID2 = "no2";
                    //var title2 = "No";
                    //var action2 = UNNotificationAction.FromIdentifier(actionID2, title2, UNNotificationActionOptions.None);

                    //// Create category
                    //var categoryID = "message";
                    //var actions = new UNNotificationAction[] { action, action2 };
                    //var intentIDs = new string[] { };
                    //var categoryOptions = new UNNotificationCategoryOptions[] { };
                    //var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

                    //// Register category
                    //var categories = new UNNotificationCategory[] { category };
                    //UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories));


                    var content = new UNMutableNotificationContent();
                    content.Title    = "Scuttle";
                    content.Subtitle = " ";
                    content.Body     = "Are you ready to share your experience?";
                    content.Badge    = 1;
                    //content.CategoryIdentifier = "message";

                    var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(2, false);
                    var requestID = "sampleRequest";
                    var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                    UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                    {
                        if (err != null)
                        {
                            // Do something with error...
                        }
                    });
                }
                else
                {
                    // create the notification
                    var notification = new UILocalNotification();
                    // set the fire date (the date time in which it will fire)
                    notification.FireDate = NSDate.FromTimeIntervalSinceNow(2);
                    // configure the alert
                    notification.AlertTitle  = "Reminder2";
                    notification.AlertAction = "Scuttle";
                    notification.AlertBody   = "Are you ready to share your experience?";

                    // modify the badge
                    notification.ApplicationIconBadgeNumber = 1;

                    // set the sound to be the default sound
                    notification.SoundName = UILocalNotification.DefaultSoundName;

                    // schedule it
                    UIApplication.SharedApplication.ScheduleLocalNotification(notification);
                }
            }
            else
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    // Create action
                    var actionID = "yes";
                    var title    = "Yes. Share my experience!";
                    var action   = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.Foreground);

                    var actionID3 = "RemindMeLater";
                    var title3    = "Yes. Remind me later to share";
                    var action3   = UNNotificationAction.FromIdentifier(actionID3, title3, UNNotificationActionOptions.None);
                    var actionID2 = "no";
                    var title2    = "Not this time";
                    var action2   = UNNotificationAction.FromIdentifier(actionID2, title2, UNNotificationActionOptions.None);

                    // Create category
                    var categoryID      = "message";
                    var actions         = new UNNotificationAction[] { action, action3, action2 };
                    var intentIDs       = new string[] { };
                    var categoryOptions = new UNNotificationCategoryOptions[] { };
                    var category        = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

                    // Register category
                    var categories = new UNNotificationCategory[] { category };
                    UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

                    var content = new UNMutableNotificationContent();
                    content.Title              = "Scuttle";
                    content.Subtitle           = " ";
                    content.Body               = "Hey! Are you at " + name + "?";
                    content.Badge              = 1;
                    content.CategoryIdentifier = "message";

                    var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(2, false);

                    var requestID = "sampleRequest";
                    var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                    UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                    {
                        if (err != null)
                        {
                            // Do something with error...
                        }
                    });
                }
                else
                {
                    // create the notification
                    var notification = new UILocalNotification();

                    // set the fire date (the date time in which it will fire)
                    notification.FireDate = NSDate.FromTimeIntervalSinceNow(5);

                    // configure the alert
                    notification.AlertTitle  = "LocationCheck";
                    notification.AlertAction = "Scuttle";
                    notification.AlertBody   = "Hey! Are you at " + name + "?";

                    // modify the badge
                    notification.ApplicationIconBadgeNumber = 1;

                    // set the sound to be the default sound
                    notification.SoundName = UILocalNotification.DefaultSoundName;

                    // schedule it
                    UIApplication.SharedApplication.ScheduleLocalNotification(notification);
                }
            }
        }