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... } }); }
public static void sendNotifications() { //Remove UNUserNotificationCenter.Current.RemoveAllPendingNotificationRequests(); MyEventEntries myEvents = new MyEventEntries(); myEvents.loadJson(loadMyDatabase()); DateTime currentTime = DateTime.Now; foreach (EventEntry tempEvent in myEvents.Events) { // Rebuild notification var content = new UNMutableNotificationContent(); content.Title = "Event: " + tempEvent.Title + " starting soon"; content.Body = "Starts at " + tempEvent.StartTime.ToString("h:mm tt") + "\nLocation: " + tempEvent.Location; content.Badge = 1; // New trigger time // var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false); var trigger = UNCalendarNotificationTrigger.CreateTrigger(DateTimeToNSDate(tempEvent.StartTime), false); // ID of Notification to be updated var requestID = tempEvent.EventID; var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger); // Add to system to modify existing Notification UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { if (err != null) { // Do something with error... } }); } }
public void Show(DateTime notifyAt) { Console.WriteLine($"Will show notification (id: {_id}) with title '{_title}' at {notifyAt}"); if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { var trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponentsFromDateTime(notifyAt), false); ShowUserNotification(trigger); } else { var notification = new UILocalNotification { FireDate = (NSDate)notifyAt, UserInfo = GetUserInfo(), }; if (_title != null) { notification.AlertTitle = _title; } if (_body != null) { notification.AlertBody = _body; } if (_actionSetId != null) { notification.Category = _actionSetId; } UIApplication.SharedApplication.ScheduleLocalNotification(notification); } }
public async static Task <bool> Schedule(string title, string body, DateTime notifyTime, int id, bool playSound = false, Dictionary <string, string> parameters = null) { if (!await Permission.LocalNotification.IsGranted()) { await Alert.Show("Permission was not granted to show local notifications."); return(false); } if (OS.IsAtLeastiOS(10)) { var trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponentsFromDateTime(notifyTime), repeats: false); ShowUserNotification(title, body, id, trigger, playSound, parameters); } else { var userData = NSDictionary.FromObjectsAndKeys( new NSObject[] { id.ToString().ToNs(), parameters.DicToString().ToNs(), title.ToNs(), body.ToNs(), (NSDate)notifyTime }, new NSObject[] { NOTIFICATION_KEY.ToNs(), NOTIFICATION_PARAM_KEY.ToNs(), NOTIFICATION_TITLE_KEY.ToNs(), NOTIFICATION_BODY_KEY.ToNs(), NOTIFICATION_Date_KEY.ToNs() }); var notification = new UILocalNotification { FireDate = (NSDate)notifyTime, AlertTitle = title, AlertBody = body, UserInfo = userData }; UIApplication.SharedApplication.ScheduleLocalNotification(notification); } return(true); }
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); }
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... } }); } }
/// <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); } }
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); }
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); }
/// <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 IssueNotificationAsync(string id, UNNotificationContent content, TimeSpan delay, Action <UNNotificationRequest> requestCreated = null) { UNCalendarNotificationTrigger trigger = null; // a non-positive delay indicates an immediate notification, which is achieved with a null trigger. if (delay.Ticks > 0) { // we're going to specify an absolute date below based on the current time and the given delay. if this time is in the past by the time // the notification center processes it (race condition), then the notification will not be scheduled. so ensure that we leave some time // and avoid the race condition. if (delay.TotalSeconds < 5) { delay = TimeSpan.FromSeconds(5); } DateTime triggerDateTime = DateTime.Now + delay; NSDateComponents triggerDateComponents = new NSDateComponents { Year = triggerDateTime.Year, Month = triggerDateTime.Month, Day = triggerDateTime.Day, Hour = triggerDateTime.Hour, Minute = triggerDateTime.Minute, Second = triggerDateTime.Second }; trigger = UNCalendarNotificationTrigger.CreateTrigger(triggerDateComponents, false); } UNNotificationRequest notificationRequest = UNNotificationRequest.FromIdentifier(id, content, trigger); requestCreated?.Invoke(notificationRequest); IssueNotificationAsync(notificationRequest); }
public void ScheduleNotification(UNNotificationContent content, DateTime notifyTime, string requestId) { Debug.WriteLine("DHB:Notifications:ScheduleNotification begin"); Foundation.NSDateComponents notificationContentNSCDate = new Foundation.NSDateComponents(); notificationContentNSCDate.Year = notifyTime.Year; notificationContentNSCDate.Month = notifyTime.Month; notificationContentNSCDate.Day = notifyTime.Day; notificationContentNSCDate.Hour = notifyTime.Hour; notificationContentNSCDate.Minute = notifyTime.Minute; notificationContentNSCDate.Second = notifyTime.Second; //notificationContentNSCDate.TimeZone = Debug.WriteLine("DHB:Notifications:ScheduleNotification sched time:" + notificationContentNSCDate.ToString()); Debug.WriteLine("DHB:Notifications:ScheduleNotification now time:" + notifyTime.ToString()); // repeats makes no sense as just a bool. what does that mean? everyday, every 5 mins, wat wat? UNNotificationTrigger trigger = UNCalendarNotificationTrigger.CreateTrigger(notificationContentNSCDate, true); //string requestId = "firstRequest"; var request = UNNotificationRequest.FromIdentifier(requestId, content, trigger); UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { if (err != null) { Debug.WriteLine("DHB:iOS:Notifications:ScheduleNotification err:" + err.ToString()); } }); Debug.WriteLine("DHB:Notifications:ScheduleNotification scheduled"); }
public void IssueNotificationAsync(string id, UNNotificationContent content, DateTime triggerDateTime, Action <UNNotificationRequest> requestCreated = null) { UNCalendarNotificationTrigger trigger = null; // we're going to specify an absolute trigger date below. if this time is in the past by the time // the notification center processes it (race condition), then the notification will not be scheduled. // so ensure that we leave some time to avoid the race condition by triggering an immediate notification // for any trigger date that is not greater than several seconds into the future. if (triggerDateTime > DateTime.Now + iOSCallbackScheduler.CALLBACK_NOTIFICATION_HORIZON_THRESHOLD) { NSDateComponents triggerDateComponents = new NSDateComponents { Year = triggerDateTime.Year, Month = triggerDateTime.Month, Day = triggerDateTime.Day, Hour = triggerDateTime.Hour, Minute = triggerDateTime.Minute, Second = triggerDateTime.Second, Calendar = NSCalendar.CurrentCalendar, TimeZone = NSTimeZone.LocalTimeZone }; trigger = UNCalendarNotificationTrigger.CreateTrigger(triggerDateComponents, false); } UNNotificationRequest notificationRequest = UNNotificationRequest.FromIdentifier(id, content, trigger); requestCreated?.Invoke(notificationRequest); IssueNotificationAsync(notificationRequest); }
/// <summary> /// Creates a scheduled toast notification with the required values. /// </summary> /// <param name="content">Text content.</param> /// <param name="title">Toast title.</param> /// <param name="deliveryTime">When to display the toast.</param> /// <returns></returns> public static ScheduledToastNotification CreateScheduledToastNotification(string content, string title, DateTimeOffset deliveryTime) { #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81 XmlDocument doc = Windows.UI.Notifications.ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02); var textElements = doc.GetElementsByTagName("text"); textElements[0].InnerText = title; textElements[1].InnerText = content; return(new ScheduledToastNotification(new Windows.UI.Notifications.ScheduledToastNotification(doc, deliveryTime))); #elif WINDOWS_PHONE throw new PlatformNotSupportedException(); #elif __ANDROID__ throw new PlatformNotSupportedException(); #elif __MAC__ NSUserNotification notification = new NSUserNotification(); notification.Title = title; notification.InformativeText = content; notification.SoundName = NSUserNotification.NSUserNotificationDefaultSoundName; notification.DeliveryDate = deliveryTime.ToNSDate(); return(notification); #elif __UNIFIED__ UNMutableNotificationContent notificationContent = new UNMutableNotificationContent(); notificationContent.Title = title; notificationContent.Body = content; notificationContent.Sound = UNNotificationSound.Default; NSDateComponents dc = NSCalendar.CurrentCalendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, deliveryTime.ToNSDate()); UNCalendarNotificationTrigger trigger = UNCalendarNotificationTrigger.CreateTrigger(dc, false); return(new ScheduledToastNotification(notificationContent, trigger)); #else return(new ScheduledToastNotification(content, title, deliveryTime)); #endif }
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); });
//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 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 async Task Send(Notification notification) { if (notification.Id == 0) { notification.Id = this.settings.IncrementValue("NotificationId"); } var access = await this.RequestAccess(); access.Assert(); var content = new UNMutableNotificationContent { Title = notification.Title, Body = notification.Message, Badge = notification.BadgeCount //LaunchImageName = "" //Subtitle = "" }; //UNNotificationAttachment.FromIdentifier("", NSUrl.FromString(""), new UNNotificationAttachmentOptions().) if (!notification.Payload.IsEmpty()) { var dict = new NSMutableDictionary(); dict.Add(new NSString("Payload"), new NSString(notification.Payload)); content.UserInfo = dict; } if (!Notification.CustomSoundFilePath.IsEmpty()) { content.Sound = UNNotificationSound.GetSound(Notification.CustomSoundFilePath); } UNNotificationTrigger trigger = null; if (notification.ScheduleDate != null) { var dt = notification.ScheduleDate.Value.ToLocalTime(); trigger = UNCalendarNotificationTrigger.CreateTrigger(new NSDateComponents { Year = dt.Year, Month = dt.Month, Day = dt.Day, Hour = dt.Hour, Minute = dt.Minute, Second = dt.Second }, false); } var request = UNNotificationRequest.FromIdentifier( notification.Id.ToString(), content, trigger ); await UNUserNotificationCenter .Current .AddNotificationRequestAsync(request); }
public void ShowNotification(string strNotificationTitle, string strNotificationSubtitle, string strNotificationDescription, string strNotificationIdItem, string strDateOrInterval, int intervalType, string extraParameters) { //intervalType: 1 - set to date | 2 - set to interval //Object creation. var notificationContent = new UNMutableNotificationContent(); //Set parameters. notificationContent.Title = strNotificationTitle; notificationContent.Subtitle = strNotificationSubtitle; notificationContent.Body = strNotificationDescription; //notificationContent.Badge = 1; notificationContent.Badge = Int32.Parse(strNotificationIdItem); notificationContent.Sound = UNNotificationSound.Default; //Set date. DateTime notificationContentDate = Convert.ToDateTime(strDateOrInterval); NSDateComponents notificationContentNSCDate = new NSDateComponents(); notificationContentNSCDate.Year = notificationContentDate.Year; notificationContentNSCDate.Month = notificationContentDate.Month; notificationContentNSCDate.Day = notificationContentDate.Day; notificationContentNSCDate.Hour = notificationContentDate.Hour; notificationContentNSCDate.Minute = notificationContentDate.Minute; notificationContentNSCDate.Second = notificationContentDate.Second; notificationContentNSCDate.Nanosecond = (notificationContentDate.Millisecond * 1000000); //Set trigger and request. var notificationRequestID = strNotificationIdItem; UNNotificationRequest notificationRequest = null; if (intervalType == 1) { var notificationCalenderTrigger = UNCalendarNotificationTrigger.CreateTrigger(notificationContentNSCDate, false); notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationCalenderTrigger); } else { var notificationIntervalTrigger = UNTimeIntervalNotificationTrigger.CreateTrigger(Int32.Parse(strDateOrInterval), false); notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationIntervalTrigger); } //Add the notification request. UNUserNotificationCenter.Current.AddNotificationRequest(notificationRequest, (err) => { if (err != null) { System.Diagnostics.Debug.WriteLine("Error : " + err); } }); }
public void SetAlarm(DateTime today, TimeSpan triggerTimeSpan, int timeOffset, string name) { //UILocalNotification notification = new UILocalNotification(); DateTime triggerDateTime = today; triggerDateTime += triggerTimeSpan - TimeSpan.FromMinutes(timeOffset); triggerDateTime = DateTime.SpecifyKind(triggerDateTime, DateTimeKind.Utc); var alarmSesi = Preferences.Get(name + "AlarmSesi", "kus") + ".wav"; try { var content = new UNMutableNotificationContent { Title = $"{name} {AppResources.VaktiHatirlatmasi}", Subtitle = AppResources.SuleymaniyeVakfiTakvimi, Body = $"{name} {AppResources.Vakti} {triggerTimeSpan}",//GetFormattedRemainingTime(), Sound = UNNotificationSound.GetSound(alarmSesi) }; //content.Badge = 9; // New trigger time NSDateComponents dateComponents = new NSDateComponents() { Calendar = NSCalendar.CurrentCalendar, Year = triggerDateTime.Year, Month = triggerDateTime.Month, Day = triggerDateTime.Day, Hour = triggerDateTime.Hour, Minute = triggerDateTime.Minute, Second = triggerDateTime.Second }; var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponents, false); // ID of Notification to be updated var requestId = "SuleymaniyeTakvimiRequest" + triggerDateTime.ToString("yyyyMMddhhmmss"); var request = UNNotificationRequest.FromIdentifier(requestId, content, trigger); // Add to system to modify existing Notification UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { if (err != null) { // Do something with error... Debug.WriteLine("Error: {0}", err); UserDialogs.Instance.Alert($"{AppResources.Hatadetaylari} {err}", AppResources.Alarmkurarkenhataolustu, AppResources.Tamam); } else { Debug.WriteLine("Notification Scheduled: {0} \n {1}", request, content); } }); } catch (Exception ex) { Debug.WriteLine("Notification Scheduling Error: {0}", ex.Message); } }
public override Task Send(Notification notification) => this.Invoke(async() => { if (notification.Id == null) { notification.GeneratedNotificationId(); } var content = new UNMutableNotificationContent { Title = notification.Title, Body = notification.Message, LaunchImageName = notification.IconName }; if (string.IsNullOrEmpty(notification.Sound)) { if (!string.IsNullOrEmpty(Notification.DefaultSound)) { notification.Sound = Notification.DefaultSound; content.Sound = UNNotificationSound.GetSound(notification.Sound); } else if (Notification.SystemSoundFallback) { // untested content.Sound = UNNotificationSound.Default; } } else { content.Sound = UNNotificationSound.GetSound(notification.Sound); } 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); });
public async void Notify(Notification notification, string id = "") { var settings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync(); if (settings.AlertSetting != UNNotificationSetting.Enabled) { ToastiOS toast = new ToastiOS(); toast.Show("Check Noti Permission"); } var noti = new UNMutableNotificationContent { Title = notification.Title, Subtitle = string.Empty, Body = notification.Text, Badge = 0 }; DateTime dt = notification.NotifyTime; var dateComponent = new NSDateComponents { Calendar = NSCalendar.CurrentCalendar, Year = dt.Year, Month = dt.Month, Day = dt.Day, Hour = dt.Hour, Minute = dt.Minute, Second = dt.Second }; var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponent, false); var request = UNNotificationRequest.FromIdentifier(string.IsNullOrWhiteSpace(id) ? notification.Id.ToString() : id, noti, trigger); UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { if (err != null) { ToastiOS toast = new ToastiOS(); toast.Show("Ooops, error"); } }); }
/// <inheritdoc /> public void Show(NotificationRequest notificationRequest) { try { if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0) == false) { return; } if (notificationRequest is null) { return; } var userInfoDictionary = new NSMutableDictionary(); userInfoDictionary.SetValueForKey( string.IsNullOrWhiteSpace(notificationRequest.ReturningData) ? NSString.Empty : new NSString(notificationRequest.ReturningData), NotificationCenter.ExtraReturnDataIos); var content = new UNMutableNotificationContent { Title = notificationRequest.Title, Body = notificationRequest.Description, Badge = notificationRequest.BadgeNumber, UserInfo = userInfoDictionary, Sound = UNNotificationSound.Default }; var trigger = UNCalendarNotificationTrigger.CreateTrigger( GetNsDateComponentsFromDateTime(notificationRequest.NotifyTime), false); _notificationList.Add(notificationRequest.NotificationId.ToString()); var request = UNNotificationRequest.FromIdentifier(notificationRequest.NotificationId.ToString(), content, trigger); UNUserNotificationCenter.Current.AddNotificationRequestAsync(request); } catch (Exception ex) { Debug.WriteLine(ex); } }
public async Task CreateDailyReminders(List <PlantActivityItem>[] listOfTasksForEveryDay, byte atHour = 8, byte atMinute = 0) { //First, remove all still pending notifications. await RemoveDailyReminders(); //Create notifications for each day. for (int i = 0; i < listOfTasksForEveryDay.Count(); i++) { var date = DateTime.Now.AddDays(i); NSDateComponents dateComponents = new NSDateComponents { Year = date.Year, Month = date.Month, Day = date.Day, Hour = atHour, Minute = atMinute }; var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponents, false); var content = new UNMutableNotificationContent { Sound = UNNotificationSound.Default, CategoryIdentifier = DAILY_NOTIFICATIONS, }; if (listOfTasksForEveryDay[i].Count == 0) { content.Title = "All good!"; content.Body = "You have no tasks for today. Enjoy the freedom! 😎"; } else { content.Title = "Your plants need you!"; content.Body = $"You have {listOfTasksForEveryDay[i].Count} task{(listOfTasksForEveryDay[i].Count > 1 ? "s" : "")} for today. Tap to see what you have to do in order to keep your (hopefully still) green friends happy. 🌿🌺"; } var request = UNNotificationRequest.FromIdentifier( $"Daily_Notification_{date.Year}_{date.Month}_{date.Day}", content, trigger); await NotificationCenter.AddNotificationRequestAsync(request); } }
private bool ScheduleLocalNotificationInternal(DayOfWeek day, String time, MedicineInfo medicine, DateTime startDate, DateTime?endDate = null) { if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { if (!String.IsNullOrEmpty(time) && Int32.TryParse(time.Split(':').FirstOrDefault(), out var hour) && Int32.TryParse(time.Split(':').LastOrDefault(), out var minutes)) { var dateComponents = new NSDateComponents(); dateComponents.Weekday = ((int)day + 1); dateComponents.Hour = hour; dateComponents.Minute = minutes; var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponents, true); var notificationContent = new UNMutableNotificationContent(); notificationContent.Title = "General.Push.Reminder.Title".Translate(); notificationContent.Body = medicine.NameFormStrength; var sound = UNNotificationSound.GetSound("alarm.caf"); notificationContent.Sound = sound; var userInfo = new Dictionary <String, String>(); userInfo.Add("day", day.ToString()); userInfo.Add("hour", hour.ToString()); userInfo.Add("minute", minutes.ToString()); userInfo.Add("medicineId", medicine.Id.ToString()); userInfo.Add("medicineName", medicine.Name); userInfo.Add("medicineStrength", medicine.Strength); userInfo.Add("startDate", startDate.ToString("dd-MM-yyyy")); userInfo.Add("endDate", endDate.HasValue ? endDate.Value.ToString("dd-MM-yyyy") : String.Empty); notificationContent.UserInfo = NSDictionary.FromObjectsAndKeys(userInfo.Values.ToArray(), userInfo.Keys.ToArray()); var notificationRequest = UNNotificationRequest.FromIdentifier($"{medicine.Id}-{day}-{hour}-{minutes}", notificationContent, trigger); UIDevice.CurrentDevice.InvokeOnMainThread(async() => await UNUserNotificationCenter.Current.AddNotificationRequestAsync(notificationRequest)); return(true); } } else { throw new NotImplementedException("Local pushnotification for iOS lower than 10 is not implemented"); } return(false); }
/// <summary> /// Show a local notification at a specified time /// </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="notifyTime">Time to show notification</param> public void Schedule(string title, string body, string id, DateTime notifyTime) { if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { var trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponentsFromDateTime(notifyTime), false); ShowUserNotification(title, body, id, trigger); } else { var notification = new UILocalNotification { FireDate = (NSDate)notifyTime, AlertTitle = title, AlertBody = body, UserInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(NotificationKey)) }; UIApplication.SharedApplication.ScheduleLocalNotification(notification); } }
public void SendNotification(string title, string message, DateTime?notifyTime = null) { // EARLY OUT: app doesn't have permissions if (!hasNotificationsPermission) { return; } messageId++; var content = new UNMutableNotificationContent() { Title = title, Subtitle = "", Body = message, Badge = 1 }; UNNotificationTrigger trigger; if (notifyTime != null) { // Create a calendar-based trigger. trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponents(notifyTime.Value), false); } else { // Create a time-based trigger, interval is in seconds and must be greater than 0. 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}"); } }); }
public void SendNotification(string title, string subtitle, string message, DateTime?notifyTime = null) { if (!hasNotificationsPermission) { return; } // 1. Creamos el Trigger de la Notificación UNNotificationTrigger trigger; if (notifyTime != null) { trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponents(notifyTime.Value), false); } else { trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.25, false); } // 2. Creamos el contenido de la Notificación var content = new UNMutableNotificationContent() { Title = title, Subtitle = subtitle, Body = message, Badge = 1 }; // 3. Creamos la Request var request = UNNotificationRequest.FromIdentifier(Guid.NewGuid().ToString(), content, trigger); // 4. Añadimos la Request al Centro de Notificaciones UNUserNotificationCenter.Current.RemoveAllPendingNotificationRequests(); UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { if (err != null) { throw new Exception($"Some Error"); } }); }
/// <summary> /// Show a local notification at a specified time /// </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="notifyTime">Time to show notification</param> public void Show(string title, string body, DateTime notifyTime, int id = 0) { if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { #pragma warning disable XI0002 // Notifies you from using newer Apple APIs when targeting an older OS version var trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponentsFromDateTime(notifyTime), false); ShowUserNotification(title, body, id, trigger); #pragma warning restore XI0002 // Notifies you from using newer Apple APIs when targeting an older OS version } else { var notification = new UILocalNotification { FireDate = (NSDate)notifyTime, AlertTitle = title, AlertBody = body, UserInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(NotificationKey)) }; UIApplication.SharedApplication.ScheduleLocalNotification(notification); } }
/// <summary> /// Show a local notification at a specified time /// </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="notifyTime">Time to show notification</param> /// <param name="customData">Custom data attached to notification</param> public void Show(string title, string body, int id, DateTime notifyTime, string customData) { if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { var trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponentsFromDateTime(notifyTime), false); ShowUserNotification(title, body, id, trigger, customData); } else { NSDictionary userInfo; if (!string.IsNullOrWhiteSpace(customData)) { userInfo = NSDictionary.FromObjectsAndKeys( new NSObject[] { NSObject.FromObject(id), NSObject.FromObject(customData), }, new NSObject[] { NSObject.FromObject(NotificationKey), NSObject.FromObject(CrossLocalNotifications.LocalNotificationCustomData), }); } else { userInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(NotificationKey)); } var notification = new UILocalNotification { FireDate = (NSDate)notifyTime, AlertTitle = title, AlertBody = body, UserInfo = userInfo, SoundName = UILocalNotification.DefaultSoundName }; UIApplication.SharedApplication.ScheduleLocalNotification(notification); } }