Example #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);
        }
Example #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
            });
        }
Example #3
0
        /// <summary>
        ///     A method to create and save a Category that will be registered for your app with all the actions
        ///     that were previously added for this Category Id and with hiddenPreviewsBodyPlaceholder and categorySummaryFormat.
        ///     See UNNotificationCategory.FromIdentifier.
        /// </summary>
        /// <remarks>
        ///     CategorySummaryFormat is only supported since iOS 12. For iOS 11 category will be created ignoring this option.
        /// </remarks>
        /// <param name="categoryId">The unique identifier for the Category. Should not be empty.</param>
        /// <param name="intentIdentifiers">
        ///     The intent identifier strings that you want to associate with notifications of this type.
        ///     The Intents framework defines constants for each type of intent that you can associate with your notifications.
        /// </param>
        /// <param name="hiddenPreviewsBodyPlaceholder">
        ///     A placeholder string to display when the user has disabled notification previews for the app.
        ///     Include the characters %u in the string to represent the number of notifications with the same thread identifier.
        /// </param>
        /// <param name="categorySummaryFormat">
        ///     Category’s summary format string.
        ///     Include the characters %u in the string to represent the number of notifications with the same thread identifier.
        /// </param>
        /// <param name="options">Additional options for handling notifications of this type.</param>
        protected void AddCategory(
            string categoryId,
            string[] intentIdentifiers,
            string hiddenPreviewsBodyPlaceholder,
            string categorySummaryFormat,
            UNNotificationCategoryOptions options)
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
            {
                _actionsForCategories.TryGetValue(categoryId, out var actions);

                var messageCategory = UNNotificationCategory.FromIdentifier(
                    categoryId,
                    actions?.ToArray() ?? new UNNotificationAction[] { },
                    intentIdentifiers,
                    hiddenPreviewsBodyPlaceholder,
                    new NSString(categorySummaryFormat),
                    options);

                NotificationCategories.Add(messageCategory);
            }
            else
            {
                AddCategory(categoryId, intentIdentifiers, hiddenPreviewsBodyPlaceholder, options);
            }
        }
        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));
        }
Example #5
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);
        }
Example #6
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()));
            }
        }
Example #7
0
        /// <summary>
        ///     A method to create and save a Category that will be registered for your app with all the actions
        ///     that were previously added for this Category Id. See UNNotificationCategory.FromIdentifier.
        /// </summary>
        /// <param name="categoryId">The unique identifier for the Category. Should not be empty.</param>
        /// <param name="intentIdentifiers">
        ///     The intent identifier strings that you want to associate with notifications of this type.
        ///     The Intents framework defines constants for each type of intent that you can associate with your notifications.
        /// </param>
        /// <param name="options">Additional options for handling notifications of this type.</param>
        protected void AddCategory(string categoryId, string[] intentIdentifiers, UNNotificationCategoryOptions options)
        {
            _actionsForCategories.TryGetValue(categoryId, out var actions);

            var messageCategory = UNNotificationCategory.FromIdentifier(
                categoryId,
                actions?.ToArray() ?? new UNNotificationAction[] { },
                intentIdentifiers,
                options);

            NotificationCategories.Add(messageCategory);
        }
        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...
                }
            });
        }
Example #10
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));
        }
Example #11
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;
        }
Example #12
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();
        }
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();

            LoadApplication(new App());

            NotificationSettings();

            var category = UNNotificationCategory.FromIdentifier("techTalks", new UNNotificationAction[] { }, new string[] { }, UNNotificationCategoryOptions.None);

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

            UNUserNotificationCenter.Current.Delegate = new NotificationDelegate();


            return(base.FinishedLaunching(app, options));
        }
Example #15
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 }));
        }
        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));
        }
        //
        // 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));
        }
Example #18
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);
        }
Example #19
0
        public static void Categoria()
        {
            Console.WriteLine("N0rf3n - EnviarNotificacion/Categoria - Begin ");
            var Accion          = new List <UNNotificationAction>();
            var IdAccion        = "Responder";
            var Titulo          = "Titulo Respuesta";
            var TituloBoton     = "Enviar";
            var MarcaAgua       = "Ingresa tu respuesta";//PlaceHolder
            var RespuestaAccion = UNTextInputNotificationAction.FromIdentifier(IdAccion, Titulo, UNNotificationActionOptions.None, TituloBoton, MarcaAgua);

            Accion.Add(RespuestaAccion);
            var IdCategoria     = "IdentificadorCategoria"; //debe conincidir con el indicado en el envio de la notificacion
            var Acciones        = Accion.ToArray();
            var Identificadores = new String[] { };
            var categoria       = UNNotificationCategory.FromIdentifier(IdCategoria, Acciones, Identificadores, UNNotificationCategoryOptions.None);//Se adjuntan los elementos de la categoria.
            var categorias      = new UNNotificationCategory[] { categoria };

            //Notification Center
            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categorias));

            Console.WriteLine("N0rf3n - EnviarNotificacion/Categoria - End ");
        }
        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));
        }
Example #21
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);
        }
        //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);
                }
            }
        }