Exemplo n.º 1
0
        public override void DidReceiveNotificationRequest(UNNotificationRequest request,
                                                           Action <UNNotificationContent> contentHandler)
        {
            ContentHandler     = contentHandler;
            BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();

            var documentIdObj = request.Content.UserInfo.ObjectForKey(new NSString("documentId"));

            if (documentIdObj != null)
            {
                var documentId = documentIdObj.ToString();
                var url        = ApiService.GetPartnerLogoUrl(documentId);

                var fileUrl      = new NSUrl(url);
                var filePath     = GetLocalFilePath();
                var isDownloaded = DownloadImageToPath(fileUrl, filePath);

                if (isDownloaded)
                {
                    const string attachmentId = "image";
                    var          options      = new UNNotificationAttachmentOptions();
                    var          attachment   = UNNotificationAttachment.FromIdentifier(attachmentId, filePath, options, out _);

                    BestAttemptContent.Attachments = new[]
                    {
                        attachment
                    };
                }
            }

            ContentHandler(BestAttemptContent);
        }
Exemplo n.º 2
0
        public void Show(LocalNotification notification)
        {
            var content = new UNMutableNotificationContent();

            content.Title    = notification.Title;
            content.Subtitle = notification.SubTitle;
            content.Body     = notification.Message;
            if (!string.IsNullOrEmpty(notification.Sound))
            {
                content.Sound = UNNotificationSound.GetSound(notification.Sound);
            }
            if (notification.Badge.HasValue)
            {
                content.Badge = notification.Badge.Value;
            }

            var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(notification.SecondsOffSet, false);
            var requestID = notification.Id.ToString();
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    // Do something with error...
                }
            });
        }
Exemplo n.º 3
0
        private async Task ScheduleLocalNotificationAsync()
        {
            _loggerService.StartMethod();

            try
            {
                var settings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();

                if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
                {
                    throw new Exception($"UserNotification is not authorized: {settings.AuthorizationStatus}");
                }

                var content = new UNMutableNotificationContent();

                content.Title = AppResources.LocalExposureNotificationTitle;
                content.Body  = AppResources.LocalExposureNotificationContent;

                var request            = UNNotificationRequest.FromIdentifier(NOTIFICATION_ID, content, null);
                var notificationCenter = UNUserNotificationCenter.Current;
                await notificationCenter.AddNotificationRequestAsync(request);
            }
            catch (Exception e)
            {
                _loggerService.Exception("Exception occurred", e);
            }

            _loggerService.EndMethod();
        }
Exemplo n.º 4
0
        //Enviar la notificación.-...
        public static void EnviarNotificacion()
        {
            Console.WriteLine("N0rf3n - EnviarNotificacion/Notificacion - Begin ");

            NSUrl ArchivoGif       = NSUrl.FromFilename("Notificacion.gif");
            var   IdArchivo        = "Not";//identificador del archivo
            var   OpcionesAdjuntar = new UNNotificationAttachmentOptions();
            var   Contenido        = new UNMutableNotificationContent();

            Contenido.Title    = "Notificacion Local";
            Contenido.Subtitle = "Suena la campana.Tirin tirin.. ";
            Contenido.Body     = "Notificacion Local";
            Contenido.Sound    = UNNotificationSound.Default;
            Contenido.Badge    = 1;

            //Se agrega la categoria.
            Contenido.CategoryIdentifier = "IdentificadorCategoria";//Se registra la categoria y se puede establecer cuando el usuario realice la escritura, caracteristicas del botón y demas.


            NSError error;

            var Adjuntar = UNNotificationAttachment.FromIdentifier(IdArchivo, ArchivoGif, OpcionesAdjuntar, out error);

            Contenido.Attachments = new UNNotificationAttachment[] { Adjuntar };

            var Disparador = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false); //Se le especifica que tarde 3 segundos.

            var IdSolicitud = "Solicitud3";                                             //id para la notificación

            var Solicitud = UNNotificationRequest.FromIdentifier(IdSolicitud, Contenido, Disparador);

            UNUserNotificationCenter.Current.AddNotificationRequest(Solicitud, (err) => { });

            Console.WriteLine("N0rf3n - EnviarNotificacion/Notificacion - End ");
        }
Exemplo n.º 5
0
        private void CreateLocalNotification(NotificationViewModel notificationViewModel, double timeIntervalTrigger)
        {
            InvokeOnMainThread(() =>
            {
                string requestID = "newMessageNotification";

                // For already delivered Notifications, the existing Notification will get updated and promoted to the top
                // of the list on the Home and Lock screens and in the Notification Center if it has already been read by the user.

                UNUserNotificationCenter.Current.GetNotificationSettings(settings => {
                    bool alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);

                    if (alertsAllowed)
                    {
                        UNMutableNotificationContent content = new UNMutableNotificationContent
                        {
                            Title = notificationViewModel.Title,
                            Body  = notificationViewModel.Body,
                            Badge = 1
                        };

                        UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(timeIntervalTrigger == 0 ? _notificationDelay : timeIntervalTrigger, false);
                        UNNotificationRequest request             = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                        UNUserNotificationCenter.Current.AddNotificationRequest(request, err => {
                            if (err != null)
                            {
                                NSErrorException e = new NSErrorException(err);
                                LogUtils.LogException(LogSeverity.ERROR, e, $"{nameof(iOSLocalNotificationsManager)}.{nameof(CreateLocalNotification)} failed");
                            }
                        });
                    }
                });
            });
        }
 async void ScheduleReminderNotification(TriggeredReminder reminder, int badge)
 {
     UNMutableNotificationContent content = new UNMutableNotificationContent()
     {
         Title = reminder.Appointment.Subject,
         Body  = CreateMessageContent(reminder),
         Sound = UNNotificationSound.Default,
         Badge = badge,
     };
     NSDateComponents dateComponents = new NSDateComponents()
     {
         Second   = reminder.AlertTime.Second,
         Minute   = reminder.AlertTime.Minute,
         Hour     = reminder.AlertTime.Hour,
         Day      = reminder.AlertTime.Day,
         Month    = reminder.AlertTime.Month,
         Year     = reminder.AlertTime.Year,
         TimeZone = NSTimeZone.SystemTimeZone,
     };
     UNCalendarNotificationTrigger trigger =
         UNCalendarNotificationTrigger.CreateTrigger(dateComponents, false);
     string identifier             = NotificationCenter.SerializeReminder(reminder);
     UNNotificationRequest request =
         UNNotificationRequest.FromIdentifier(identifier, content, trigger);
     await notificationCenter.AddNotificationRequestAsync(request);
 }
Exemplo n.º 7
0
        private void ShowNotification(string title, string message)
        {
            //var alert = new UIAlertView(title ?? "Title", message ?? "Message", null, "Cancel", "OK");
            //alert.Show();

            InvokeOnMainThread(() => {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    var content = new UNMutableNotificationContent {
                        Title    = title,
                        Subtitle = message,
                        Sound    = UNNotificationSound.Default,
                        Badge    = 0
                    };
                    NSObject objTrue = new NSNumber(true);
                    NSString key     = new NSString("shouldAlwaysAlertWhileAppIsForeground");
                    content.SetValueForKey(objTrue, key);
                    key = new NSString("shouldAddToNotificationsList");
                    content.SetValueForKey(objTrue, key);

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

                    UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                        if (err != null)
                        {
                            Console.WriteLine("Error: " + err.LocalizedDescription);
                        }
                    });
                }
            });
        }
Exemplo n.º 8
0
        partial void SimpleNotificationTapped(Foundation.NSObject sender)
        {
            // Create content
            var content = new UNMutableNotificationContent();

            content.Title    = "Notification Title";
            content.Subtitle = "Notification Subtitle";
            content.Body     = "This is the message body of the notification.";

            // 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);
                }
            });
        }
Exemplo n.º 9
0
        // Show local notifications using the UNUserNotificationCenter using a notification trigger (iOS 10+ only)
        static void ShowUserNotification(string title, string body, int id, UNNotificationTrigger trigger)
        {
            if (!UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                return;
            }

            var content = new UNMutableNotificationContent()
            {
                Title = title,
                Body  = body,
                Badge = 1,
            };

            var request = UNNotificationRequest.FromIdentifier(id.ToString(), content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) =>
            {
                if (error != null)
                {
                    Crashes.TrackError(new Exception(error.ToString()));
#if DEBUG
                    Device.BeginInvokeOnMainThread(() => throw new Exception("Notification error. " + error));
#endif
                }
            });
        }
Exemplo n.º 10
0
        /// <summary>
        /// Schedules the notification.
        /// </summary>
        /// <returns> GUID for the notification. Can be used to cancel it in the future. Will return NULL if inapropriate values are passed in</returns>
        /// <param name="timeInterval">Time interval in seconds. MUST BE GREATER THAN 0.</param>
        /// <param name="repeats">If set to <c>true</c> repeats.</param>
        /// <param name="title">Title.</param>
        /// <param name="body">Body.</param>
        public string ScheduleNotification(double timeInterval, bool repeats, string title, string body)
        {
            if (timeInterval <= 0)
            {
                return(null);
            }

            var content = new UNMutableNotificationContent();

            content.Title = title;
            content.Body  = body;

            var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(timeInterval, repeats);
            var requestID = Guid.NewGuid().ToString("D");
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                if (err != null)
                {
                    Console.WriteLine(err.Description);
                }
            });

            return(requestID);
        }
Exemplo n.º 11
0
        partial void SendNotification(UIButton sender)
        {
            var content = new UNMutableNotificationContent();

            content.Title = "View Alert";
            content.Body  = "Your 10 second alert has fired!";
            content.Sound = UNNotificationSound.Default;
            content.Badge = 1;

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

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

            // schedule it
            UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) =>
            {
                if (error != null)
                {
                    Console.WriteLine($"Error: {error.LocalizedDescription ?? ""}");
                }
                else
                {
                    Console.WriteLine("Scheduled...");
                }
            });
        }
Exemplo n.º 12
0
        public async void ScheduleNextDisable(Profile prof)
        {
            bool shouldApply = false;

            bool[] days = prof.Days;
            foreach (bool day in days)
            {
                shouldApply |= day;
            }
            if (!shouldApply)
            {
                return;
            }

            var content = new UNMutableNotificationContent();

            content.Title    = "Profil: " + prof.Name;
            content.Subtitle = "Anrufe sind jetzt erlaubt.";
            content.Body     = "";
            content.UserInfo = new NSDictionary("ProfileName", prof.Name);
            content.Sound    = UNNotificationSound.Default;

            var targetTime = GetTargetTime(prof, false);
            var trigger    = UNCalendarNotificationTrigger.CreateTrigger(targetTime, repeats: false);
            var requestID  = prof.Name + "Disable";
            var request    = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            await UNUserNotificationCenter.Current.AddNotificationRequestAsync(request);
        }
Exemplo n.º 13
0
        async partial void ScheduleUnthreadedNotification(UIButton sender)
        {
            var center = UNUserNotificationCenter.Current;

            UNNotificationSettings settings = await center.GetNotificationSettingsAsync();

            if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
            {
                return;
            }

            string appointment = appointments[unthreadedMessagesSent % appointments.Length];

            var content = new UNMutableNotificationContent()
            {
                Title           = appointment,
                Body            = "See you for your appointment today at 2:00pm!",
                SummaryArgument = appointment
            };

            var request = UNNotificationRequest.FromIdentifier(
                Guid.NewGuid().ToString(),
                content,
                UNTimeIntervalNotificationTrigger.CreateTrigger(1, false)
                );

            center.AddNotificationRequest(request, null);

            unthreadedMessagesSent += 1;
        }
Exemplo n.º 14
0
        public void NotifyLocal()
        {
            System.Diagnostics.Debug.WriteLine("Call NotifyLocal");
            // center.
            var content = new UNMutableNotificationContent();

            content.Title    = "Notification Title";
            content.Subtitle = "Notification Subtitle";
            content.Body     = "This is the message body of the notification.";
            content.Sound    = UNNotificationSound.Default;
            content.Badge    = 1;

            // Fire trigger in twenty seconds
            var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(2, false); // more then 0
            var requestID = "sampleRequest";
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null) // Report error
                {
                    Console.WriteLine($"Error: {err}");
                }
                else   // Report Success
                {
                    Console.WriteLine($"Notification Scheduled: {request}");
                }
            });
        }
Exemplo n.º 15
0
        public async Task Send(Notification notification)
        {
            //var permission = await this.RequestAccess();
            var content = new UNMutableNotificationContent
            {
                Title = notification.Title,
                Body  = notification.Message
                        //Badge=
                        //LaunchImageName = ""
                        //Subtitle = ""
            };

            //UNNotificationAttachment.FromIdentifier("", NSUrl.FromString(""), new UNNotificationAttachmentOptions().)
            if (!String.IsNullOrWhiteSpace(notification.Payload))
            {
                content.UserInfo.SetValueForKey(new NSString(notification.Payload), new NSString("Payload"));
            }

            if (!String.IsNullOrWhiteSpace(notification.Sound))
            {
                content.Sound = UNNotificationSound.GetSound(notification.Sound);
            }

            var request = UNNotificationRequest.FromIdentifier(
                notification.Id.ToString(),
                content,
                UNTimeIntervalNotificationTrigger.CreateTrigger(3, false)
                );
            await UNUserNotificationCenter
            .Current
            .AddNotificationRequestAsync(request);
        }
Exemplo n.º 16
0
        public void Notify(Notification message)
        {
            try
            {
                var content = new UNMutableNotificationContent
                {
                    Title = "Alert",
                    Body  = message.Title
                };

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

                content.UserInfo = new NSDictionary <NSString, NSString>(new NSString[] {
                    new NSString(REQUEST_ID), new NSString("TEXT_BODY")
                },
                                                                         new NSString[] { new NSString(message.Url), new NSString(message.Title) });

                var request = UNNotificationRequest.FromIdentifier(REQUEST_ID, content, trigger);


                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                {
                    if (err != null)
                    {
                        Debug.WriteLine(err.DebugDescription);
                    }
                    else
                    {
                    }
                });
            }
            catch (Exception bug)
            {
            }
        }
Exemplo n.º 17
0
        public void ScheduleNewPicture(DateTime timeSetting)
        {
            string id      = NotificationType.NewPicture.ToString();
            var    content = new UNMutableNotificationContent
            {
                Title    = Notifications.Title.NewPicture,
                Subtitle = "",
                Body     = Notifications.Body.NewPicture,
                Badge    = 0,
            };

            var newPictureTime = timeSetting.ToLocalTime();
            var time           = new NSDateComponents
            {
                Year   = newPictureTime.Year,
                Month  = newPictureTime.Month,
                Day    = newPictureTime.Day,
                Hour   = newPictureTime.Hour,
                Minute = newPictureTime.Minute,
                Second = newPictureTime.Second
            };
            var trigger = UNCalendarNotificationTrigger.CreateTrigger(time, false);

            var req = UNNotificationRequest.FromIdentifier(id, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(req, null);
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        public async void Show(NotificationRequest notificationRequest)
        {
            try
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0) == false)
                {
                    return;
                }

                if (notificationRequest is null)
                {
                    return;
                }

                var userInfoDictionary = new NSMutableDictionary();

                if (string.IsNullOrWhiteSpace(notificationRequest.ReturningData) == false)
                {
                    using (var returningData = new NSString(notificationRequest.ReturningData))
                    {
                        userInfoDictionary.SetValueForKey(
                            string.IsNullOrWhiteSpace(notificationRequest.ReturningData)
                                ? NSString.Empty
                                : returningData, NotificationCenter.ExtraReturnDataIos);
                    }
                }

                using (var content = new UNMutableNotificationContent
                {
                    Title = notificationRequest.Title,
                    Body = notificationRequest.Description,
                    Badge = notificationRequest.BadgeNumber,
                    UserInfo = userInfoDictionary,
                    Sound = UNNotificationSound.Default
                })
                {
                    if (string.IsNullOrWhiteSpace(notificationRequest.Sound) == false)
                    {
                        content.Sound = UNNotificationSound.GetSound(notificationRequest.Sound);
                    }

                    using (var notifyTime = GetNsDateComponentsFromDateTime(notificationRequest.NotifyTime))
                    {
                        using (var trigger = UNCalendarNotificationTrigger.CreateTrigger(notifyTime, false))
                        {
                            var notificationId =
                                notificationRequest.NotificationId.ToString(CultureInfo.CurrentCulture);

                            var request = UNNotificationRequest.FromIdentifier(notificationId, content, trigger);

                            await UNUserNotificationCenter.Current.AddNotificationRequestAsync(request).ConfigureAwait(false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
Exemplo n.º 19
0
        public void SetSpecificReminder(string title, string message, DateTime dateTime)
        {
            // TODO add this check further up the line, so that the user can't create reminders unless approved
            if (CheckApproval() == true)
            {
                var content = new UNMutableNotificationContent();
                content.Title = title;
                content.Body  = message;
                content.Badge = 1;

                var dateComp = new NSDateComponents();
                dateComp.Year   = dateTime.Year;
                dateComp.Day    = dateTime.Day;
                dateComp.Hour   = dateTime.Hour;
                dateComp.Minute = dateTime.Minute;
                dateComp.Second = dateTime.Second;

                var trigger   = UNCalendarNotificationTrigger.CreateTrigger(dateComp, false);
                var requestID = "testRequest";
                var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                    if (err != null)
                    {
                        // Do something with error...
                    }
                });
            }
        }
        /// <summary>
        ///     Show a local notification
        /// </summary>
        /// <param name="title">Title of the notification</param>
        /// <param name="body">Body or description of the notification</param>
        /// <param name="id">Id of the notification</param>
        /// <param name="notificationDateTime">Time to show notification</param>
        public void Notify(string title, string body, DateTime notificationDateTime, int id = 0)
        {
            if (!_hasNotificationPermissions)
            {
                return;
            }
            UNMutableNotificationContent content = new UNMutableNotificationContent
            {
                Title = title,
                Body  = body,
                Sound = UNNotificationSound.Default
            };
            NSDateComponents dateComponent = new NSDateComponents
            {
                Month  = notificationDateTime.Month,
                Day    = notificationDateTime.Day,
                Year   = notificationDateTime.Year,
                Hour   = notificationDateTime.Hour,
                Minute = notificationDateTime.Minute,
                Second = notificationDateTime.Second
            };
            UNCalendarNotificationTrigger trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponent, false);

            BaseNotify(id, content, trigger);
        }
        public void SchedulingNotifications(string Title, string Subtitle, string Body, string requestID, DateTime inputDate, Page page)
        {
            bool alertsAllowed = true;

            UNUserNotificationCenter.Current.GetNotificationSettings((settings) =>
            {
                alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
            });

            var content = new UNMutableNotificationContent();

            content.Title    = Title;
            content.Subtitle = Subtitle;
            content.Body     = Body;
            content.Badge    = 1;

            var date = new NSDateComponents();

            date.Hour  = inputDate.Hour;
            date.Day   = inputDate.Day;
            date.Month = inputDate.Month;
            date.Year  = inputDate.Year;

            var trigger = UNCalendarNotificationTrigger.CreateTrigger(date, true);

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

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                if (err != null)
                {
                    // Do something with error...
                }
            });
        }
        private async Task ScheduleNotification(string id, UNMutableNotificationContent content, DateTime deliveryTime)
        {
            try
            {
                // Don't schedule unless 5 secs in future, otherwise possibly throws assertion error
                double seconds = (deliveryTime - DateTime.Now).TotalSeconds;
                if (seconds < 5)
                {
                    return;
                }

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

                // This code doesn't seem to work
                //var components = new NSDateComponents();
                //components.Second += 5;
                //var trigger = UserNotifications.UNCalendarNotificationTrigger.CreateTrigger(components, false);

                var request = UNNotificationRequest.FromIdentifier(id, content, trigger);

                await UNUserNotificationCenter.Current.AddNotificationRequestAsync(request);
            }
            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }
        }
Exemplo n.º 23
0
        private async void createNotification()
        {
            try
            {
                var center = UNUserNotificationCenter.Current;

                UNNotificationSettings settings = await center.GetNotificationSettingsAsync();

                if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
                {
                    return;
                }

                var content = new UNMutableNotificationContent()
                {
                    ThreadIdentifier = GROUP_NAME,
                    Title            = "Javier Cantos",
                    Body             = "Mensaje de prueba",
                    SummaryArgument  = "Javier Cantos"
                };

                var request = UNNotificationRequest.FromIdentifier(
                    Guid.NewGuid().ToString(),
                    content,
                    null
                    );

                center.AddNotificationRequest(request, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 24
0
 public override int ScheduleLocalNotification(string body, int delay)
 {
     if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
     {
         UNUserNotificationCenter     center  = UNUserNotificationCenter.Current;
         UNMutableNotificationContent content = new UNMutableNotificationContent();
         content.Body  = body;
         content.Sound = UNNotificationSound.Default;
         UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(delay, false);
         UNNotificationRequest             request = UNNotificationRequest.FromIdentifier(StringIdentifierFromInt(LocalNotificationUid), content, trigger);
         center.AddNotificationRequest(request, (NSError error) =>
         {
             if (error != null)
             {
                 Console.WriteLine("Something went wrong:" + error);
             }
         });
     }
     else
     {
         UILocalNotification localNotification = new UILocalNotification();
         localNotification.FireDate  = NSDate.FromTimeIntervalSinceNow(delay);
         localNotification.AlertBody = body;
         localNotification.TimeZone  = NSTimeZone.DefaultTimeZone;
         localNotification.UserInfo  = NSDictionary.FromObjectAndKey(NSNumber.FromInt32(LocalNotificationUid), new NSString(PWMLocalNotificationUidKey));
         UIApplication.SharedApplication.ScheduleLocalNotification(localNotification);
     }
     return(LocalNotificationUid++);
 }
Exemplo n.º 25
0
        public void ScheduleDailyNotification(DateTime notificationTime)
        {
            var content = new UNMutableNotificationContent()
            {
                Title    = "Daily Reflection",
                Subtitle = "",
                Body     = "Time for the daily reflection!",
                Badge    = 1
            };

            var time = notificationTime.TimeOfDay;

            var dateComponents = new NSDateComponents
            {
                Hour   = time.Hours,
                Minute = time.Minutes
            };

            var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponents, repeats: true);

            var request = UNNotificationRequest.FromIdentifier(MessageId.ToString(), content, trigger);

            CancelNotifications();

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    throw new Exception($"Failed to schedule notification: {err}");
                }
            });
        }
        public int ScheduleNotification(string title, string message)
        {
            if (!_hasNotificationsPermission)
            {
                return(-1);
            }

            _messageId++;

            var content = new UNMutableNotificationContent()
            {
                Title    = title,
                Subtitle = "",
                Body     = message,
                Badge    = 1,
            };

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

            var request = UNNotificationRequest.FromIdentifier(_messageId.ToString(), content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    throw new Exception($"Failed to schedule notification: {err}");
                }
            });

            return(_messageId);
        }
        public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action <UNNotificationContent> contentHandler)
        {
            ContentHandler     = contentHandler;
            BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();

            CountlyNotificationService.DidReceiveNotificationRequest(request, contentHandler);
        }
Exemplo n.º 28
0
        public override Task Send(Notification notification) => this.Invoke(async() =>
        {
            if (notification.Id == null)
            {
                notification.Id = GeneratedNotificationId(notification);
            }

            var content = new UNMutableNotificationContent
            {
                Title = notification.Title,
                Body  = notification.Message
            };
            if (String.IsNullOrWhiteSpace(notification.Sound))
            {
                //content.Sound = UNNotificationSound.GetSound(notification.Sound);
                content.Sound = UNNotificationSound.GetSound(UILocalNotification.DefaultSoundName);
            }

            var dt      = notification.SendTime;
            var request = UNNotificationRequest.FromIdentifier(
                notification.Id.Value.ToString(),
                content,
                UNCalendarNotificationTrigger.CreateTrigger(new NSDateComponents
            {
                Year   = dt.Year,
                Month  = dt.Month,
                Day    = dt.Day,
                Hour   = dt.Hour,
                Minute = dt.Minute,
                Second = dt.Second
            }, false)
                );
            await UNUserNotificationCenter.Current.AddNotificationRequestAsync(request);
        });
Exemplo n.º 29
0
        //public int NumberOfNotifi()
        //{
        //    int output = 0;
        //    foreach (var item in tasks)
        //    {
        //        if (item.Notification)
        //        {
        //            if (0 <= DateTime.Compare(DateTime.Now, Extensions.NSDateToDateTime(item.DateAndTime)))
        //            {
        //                output++;
        //            }
        //        }
        //    }
        //    return output;
        //}

        private void AddNewNotification(Task task)
        {
            var content = new UNMutableNotificationContent();

            content.Title = task.Name + " - " + task.Cattegory;
            content.Body  = task.ShortLabel;
            content.Badge = 0;

            NSDateComponents dateNotifiComp = new NSDateComponents();
            DateTime         dateNotifi     = Extensions.NSDateToDateTime(task.DateAndTime);

            dateNotifiComp.Minute = dateNotifi.Minute;
            dateNotifiComp.Hour   = dateNotifi.Hour;
            dateNotifiComp.Day    = dateNotifi.Day;
            dateNotifiComp.Month  = dateNotifi.Month;
            dateNotifiComp.Year   = dateNotifi.Year;

            var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateNotifiComp, false);

            dateNotifi = dateNotifi.AddSeconds(-dateNotifi.Second);
            var requestID = task.Name + dateNotifi.ToString();
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            Console.WriteLine(requestID);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                if (err != null)
                {
                    System.Console.WriteLine(err);
                }
            });
        }
        public int ScheduleNotification(string title, string message)
        {
            // EARLY OUT: app doesn't have permissions
            if (!hasNotificationsPermission)
            {
                return(-1);
            }

            messageId++;

            var content = new UNMutableNotificationContent()
            {
                Title    = title,
                Subtitle = "",
                Body     = message,
                Badge    = 1
            };

            // Local notifications can be time or location based
            // Create a time-based trigger, interval is in seconds and must be greater than 0
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.25, false);

            var request = UNNotificationRequest.FromIdentifier(messageId.ToString(), content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    throw new Exception($"Failed to schedule notification: {err}");
                }
            });

            return(messageId);
        }
Exemplo n.º 31
0
		public void AskQuestion (string question, bool sendNotification)
		{
			// Anything to process?
			if (question == "") return;

			// Add question to history
			ChatHistory.Text += string.Format ("\nHuman: {0}", question);

			// Clear input
			ChatInput.Text = "";

			// Get response
			var response = Eliza.ProcessInput (question);

			// Add Eliza's response to history
			ChatHistory.Text += string.Format ("\nEliza: {0}\n", response);

			// Scroll output to bottom
			var bottom = new NSRange (ChatHistory.Text.Length - 1, 1);
			ChatHistory.ScrollRangeToVisible (bottom);

			// Sending a user notification as well
			if (sendNotification) {
				var content = new UNMutableNotificationContent ();
				content.Title = "ElizaChat Question";
				content.Subtitle = question;
				content.Body = response;

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

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

				UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => {
					if (err != null) {
						Console.WriteLine ("Error: {0}", err);
					}
				});
			}
		}