示例#1
0
        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}");
                }
            });
        }
示例#2
0
        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");
                }
            });
        }
示例#3
0
        /// <summary>
        /// Display a simple notification with an optional large image
        /// </summary>
        /// <param name="title">Heading for the notification</param>
        /// <param name="text">The message below the title</param>
        /// <param name="id">Unique id for the notification</param>
        /// <param name="bmpData">Data for the large image</param>
        public void DisplayDefaultNotification(string title, string text, IComparable id = null, byte[] bmpData = null)
        {
            if (id == null)
            {
                id = DefaultNotificationId;
            }

            UNUserNotificationCenter.Current.GetNotificationSettings(settings =>
            {
                // Make sure alerts are still allowed
                if (settings.AlertSetting != UNNotificationSetting.Enabled)
                {
                    return;
                }

                var content = new UNMutableNotificationContent
                {
                    Title = title,
                    Body  = text,
                    Sound = UNNotificationSound.Default
                };

                if (bmpData != null)
                {
                    // Maybe someone can fix this in the future; the image should be displayed along the notification
                    //UIImage image = ConvertDataToImage(bmpData);
                    //content.Attachments = new UNNotificationAttachment[];
                }

                var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0, false);
                var request = UNNotificationRequest.FromIdentifier((string)id, content, trigger);

                UNUserNotificationCenter.Current.AddNotificationRequest(request, error =>
                {
                    if (error != null)
                    {
                        // TODO: handle error if necessary
                    }
                });
            });
        }
示例#4
0
        public void SendNotification(RideDetails rideDetails)
        {
            UNMutableNotificationContent content = new UNMutableNotificationContent();

            content.Title = "New Trip Request";
            content.Body  = $"Trip to {rideDetails.DestinationAddress}";
            content.Badge = 0;
            content.Sound = UNNotificationSound.GetSound("alertios.aiff");

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

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) =>
            {
                if (error != null)
                {
                    // do something here.
                }
            });
        }
示例#5
0
        public void RegisterNotification(string title, string body)
        {
            UNUserNotificationCenter center = UNUserNotificationCenter.Current;

            //creat a UNMutableNotificationContent which contains your notification content
            UNMutableNotificationContent notificationContent = new UNMutableNotificationContent();

            notificationContent.Title = title;
            notificationContent.Body  = body;

            notificationContent.Sound = UNNotificationSound.Default;

            UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

            UNNotificationRequest request = UNNotificationRequest.FromIdentifier("FiveSecond", notificationContent, trigger);


            center.AddNotificationRequest(request, (NSError obj) =>
            {
            });
        }
        private void ScheduleTask()
        {
            var content = new UNMutableNotificationContent();

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

            //var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(10, false);
            var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(60, true);
            var requestID = "sampleRequest";
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                if (err != null)
                {
                    // Do something with error...
                }
            });
        }
示例#7
0
        /// <summary>
        /// ローカル通知を送信します。
        /// </summary>
        /// <param name="title">通知のタイトル</param>
        /// <param name="body">通知のメッセージ</param>
        public static void Send(String title, String body)
        {
            var content = new UNMutableNotificationContent()
            {
                Title = title,
                Body  = body,
                Sound = UNNotificationSound.Default,
                Badge = 0,
            };

            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);
            var request = UNNotificationRequest.FromIdentifier("LocationNotification", content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) =>
            {
                if (error != null)
                {
                    Console.Error.WriteLine("プッシュ通知送信に失敗しました。\n{0}", error.ToString());
                }
            });
        }
        public static void Display(DisplayedPromptsModel displayedPrompts)
        {
            // Get current notification settings
            //UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {
            //    var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
            //});

            var  plist = NSUserDefaults.StandardUserDefaults;
            bool enableNotifications = plist.BoolForKey("enableNotifications");

            if (!enableNotifications)
            {
                return;
            }

            var content = new UNMutableNotificationContent();

            content.Title = displayedPrompts.Category;
            //content.Subtitle = displayedPrompts.Category;
            content.Body  = displayedPrompts.Task;
            content.Badge = NSNumber.FromInt32(Convert.ToInt32(UIApplication.SharedApplication.ApplicationIconBadgeNumber) + 1);

            var timeInterval = new NSDateComponents();

            timeInterval.Second = 1;

            //var trigger = UNCalendarNotificationTrigger.CreateTrigger(timeInterval, false);
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

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

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    Console.WriteLine("something went wrong");
                }
            });
        }
示例#9
0
        public int ScheduleNotification(string title, string message)
        {
            // EARLY OUT: app doesn't have permissions
            if (!hasNotificationsPermission)
            {
                return(-1);
            }

            messageId++;

            try
            {
                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}");
                    }
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return(messageId);
        }
示例#10
0
        public void TestNote(string title, string message)
        {
            // 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 trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(15, false);
                var requestID = "testRequest";
                var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                    if (err != null)
                    {
                        // Do something with error...
                    }
                });
            }
        }
示例#11
0
        /// <summary>
        /// 通知
        /// </summary>
        /// <param name="title">タイトル</param>
        /// <param name="subTitle">サブタイトル</param>
        /// <param name="message">本文</param>
        /// <param name="sec">表示秒数</param>
        /// <param name="isRepeat">繰り返し表示するか</param>
        /// <param name="isUseBadge">バッジ表示するか</param>
        public void Show(string title, string subTitle, string message, int sec = 1, bool isRepeat = false, bool isUseBadge = true)
        {
            // メインスレッドにて処理
            UIApplication.SharedApplication.InvokeOnMainThread(delegate
            {
                var content = new UNMutableNotificationContent();                               // 表示内容
                var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(sec, isRepeat);   // 表示条件

                // 表示テキスト
                content.Title    = title;
                content.Subtitle = subTitle;
                content.Body     = message;

                // 表示サウンド
                content.Sound = UNNotificationSound.Default;

                // 解除する際のキー設定
                content.UserInfo = NSDictionary.FromObjectAndKey(new NSString(_RequestValue), new NSString(_RequestID));

                // ローカル通知の予約
                var request = UNNotificationRequest.FromIdentifier(_RequestID, content, trigger);
                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                {
#if DEBUG
                    // エラー発生チェック
                    if (err != null)
                    {
                        System.Diagnostics.Debug.WriteLine(err.LocalizedFailureReason + "\n" + err.LocalizedDescription);
                    }
#endif
                });

                // アイコン上に表示されるバッジ数値更新
                if (isUseBadge)
                {
                    UIApplication.SharedApplication.ApplicationIconBadgeNumber = 1;
                }
            });
        }
示例#12
0
        public int ScheduleNotification(string title, string message)
        {
            // EARLY OUT: app doesn't have permissions

            /*
             * if (!hasNotificationsPermission)
             * {
             *  return -1;
             * }
             */

            messageId++;

            var requestID = "notifyKey";
            var content   = new UNMutableNotificationContent()
            {
                Title    = title,
                Subtitle = title,
                Body     = message,
                Sound    = UNNotificationSound.Default,
                Badge    = 1,
                UserInfo = NSDictionary.FromObjectAndKey(new NSString("notifyValue"), new NSString("notifyKey"))
            };

            // 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(5, false);
            var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    throw new Exception($"Failed to schedule notification: {err}");
                }
            });
            UIApplication.SharedApplication.ApplicationIconBadgeNumber += 1;
            return(messageId);
        }
示例#13
0
        private void SentNotificationWithoutSubscribe(Message newMessage)
        {
            var content = new UNMutableNotificationContent();

            content.Title = "Съобщение от ВиК Русе";

            foreach (var item in newMessage.Messages)
            {
                //  Generate a message summary for the body of the notification:
                content.Subtitle = ($"{item.ToString()}");
            }

            content.Sound = UNNotificationSound.Default;


            var notification = new UILocalNotification();
            // Fire trigger in one seconds
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);

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

            //Here I set the Delegate to handle the user tapping on notification
            // UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    // Report error
                    System.Console.WriteLine("Error: {0}", err);
                }
                else
                {
                    // Report Success
                    System.Console.WriteLine("Notification Scheduled: {0}", request);
                }
            });
        }
示例#14
0
        public void DisplayNotification(string title, string subtitle, string body, string requestId)
        {
            var content = new UNMutableNotificationContent();

            // Compose the notification
            if (title != null && title.Length > 0)
            {
                content.Title = title;
            }
            else
            {
                content.Title = "-";
            }
            if (subtitle != null && subtitle.Length > 0)
            {
                content.Subtitle = subtitle;
            }
            if (body != null && body.Length > 0)
            {
                content.Body = body;
            }
            else
            {
                content.Body = "See the Pops page for details";
            }
            content.Sound = UNNotificationSound.GetSound("bubblepop.wav");

            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false); // 1 second delay, do not repeat.

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

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    Debug.WriteLine(">>>>> Message error: " + err.DebugDescription);
                }
            });
        }
        public static void sendNotification(string title, string body)
        {
            var content = new UNMutableNotificationContent();

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

            // New trigger time
            // var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
            // ID of Notification to be updated
            var requestID = "TTCAdminMessage";
            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...
                }
            });
        }
示例#16
0
        public void ShowNotification(string title, string subtitle, string body, int id, TimeSpan waitInterval)
        {
            try
            {
                UNMutableNotificationContent content = CreateNotificationContent(title, subtitle, body);
                var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(waitInterval.TotalSeconds, false);
                var request = UNNotificationRequest.FromIdentifier(id.ToString(), content, trigger);

                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                {
                    if (err == null)
                    {
                        SystemSound.Vibrate.PlayAlertSound();
                    }
                    else
                    {
                    }
                });
            }
            catch (Exception)
            {
            }
        }
示例#17
0
        public static void ScheduleAppTerminatedNotification()
        {
            UNMutableNotificationContent content = new UNMutableNotificationContent
            {
                Title = AppResources.TerminationNotificationTitle,
                Body  = AppResources.TerminationNotificationBody
            };

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

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

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

            // Needed to get the notification to schedule
            Thread.Sleep(2);
        }
示例#18
0
        public async Task Send(Notification notification)
        {
            if (notification.Id == 0)
            {
                notification.Id = this.settings.IncrementValue("NotificationId");
            }

            //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);
        }
示例#19
0
 public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler)
 {
     CrossBadge.Current.SetBadge(1);
     if (NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("UserNotificaiton")) != null && NSUserDefaults.StandardUserDefaults.BoolForKey("UserNotificaiton") && !string.IsNullOrEmpty(NSUserDefaults.StandardUserDefaults.StringForKey("MEI_UserID")))
     {
         string title        = (userInfo[new NSString("header")] as NSString).ToString();
         string message      = (userInfo[new NSString("message")] as NSString).ToString();
         string imageURL     = (userInfo[new NSString("image")] as NSString).ToString();
         var    notificaiton = new UNMutableNotificationContent();
         notificaiton.Title = title;
         notificaiton.Body  = App.HtmlToPlainText(message);
         notificaiton.Badge = 1;
         var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);
         var requestID = "MEI_LocalNotification";
         var request   = UNNotificationRequest.FromIdentifier(requestID, notificaiton, trigger);
         UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
         {
             if (err != null)
             {
             }
         });
         try
         {
             if (App.Current.MainPage != null)
             {
                 if (App.Current.MainPage.GetType() == typeof(HomeLayout))
                 {
                     ((HomeLayout)App.Current.MainPage).ResetRegisteredDomainList();
                 }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.ToString());
         }
     }
 }
        public void CreateNotification()
        {
            // Get current notification settings
            UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {
                var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
            });
            var content = new UNMutableNotificationContent();

            content.Title    = "Beau Travail !";
            content.Subtitle = "Ta session de travail a duré " + TimerInfo.hour.ToString() + " h et " + TimerInfo.min.ToString() + " minutes !";
            content.Body     = "";
            content.Badge    = 1;
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

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

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                if (err != null)
                {
                    // Do something with error...
                }
            });
        }
示例#21
0
        // emulate firebase message
        public int ScheduleNotification(string message)
        {
            // EARLY OUT: app doesn't have permissions
            if (!hasNotificationsPermission)
            {
                return(-1);
            }

            messageId++;

            var content = new UNMutableNotificationContent()
            {
                Title    = "Atomex",
                Subtitle = "",
                Body     = message,
                Sound    = UNNotificationSound.Default
            };

            // 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(5, false);

            //var request = UNNotificationRequest.FromIdentifier("swap", content, trigger);
            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 static void AddLocalNotification(NotificationModel model)
        {
            model.NotificationType = Enums.NotificationType.LocalNotification;
            var     trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
            var     requestID = Guid.NewGuid().ToString();
            var     jsonData  = JsonConvert.SerializeObject(model);
            NSError error     = new NSError();
            //NSDictionary jsonDict = (NSDictionary)NSJsonSerialization.Deserialize("{ \"Action\": {\"ActionScreen\":\"FEED\",\"ActionParamDict\":{\"FeedID\":\"11376388\",\"FeedURL\":\"https://socialladder.rkiapps.com/SocialLadderAPI/api/v1/feed?deviceUUID=3C98514894414A379F2A73C916A63FB7&ForFeedID=11376388&AreaGUID=5CFAF4F1-5DEF-407F-A35A-561C1E5F5AD0\",\"FeedItemPosition\":\"1\"}},\"Message\":\"xxx123 commented on your feed\",\"AreaGUID\":\"5CFAF4F1-5DEF-407F-A35A-561C1E5F5AD0\",\"NotificationType\":1 }",0, out error);
            NSDictionary jsonDict = (NSDictionary)NSJsonSerialization.Deserialize(jsonData, 0, out error);

            jsonDict = jsonDict.RemoveNullValues();
            var content = new UNMutableNotificationContent {
                Title = string.Empty, Subtitle = string.Empty, Body = model.Message, Badge = 1, UserInfo = jsonDict
            };
            var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    System.Diagnostics.Debug.WriteLine(err);
                }
            });
        }
示例#23
0
        public int ScheduleNotification(string title, string message)
        {
            // Check permission
            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, (error) =>
            {
                if (error != null)
                {
                    throw new Exception($"Failed to schedule notification: {error}");
                }
            });

            UIApplication.SharedApplication.ApplicationIconBadgeNumber = messageId;

            return(messageId);
        }
示例#24
0
        public void On(string title, string subTitle, string body)
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                    var content      = new UNMutableNotificationContent();
                    content.Title    = title;
                    content.Subtitle = title;
                    content.Body     = body;
                    content.Sound    = UNNotificationSound.Default;

                    var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);
                    //5秒後に通知、リピートしない
                    //日時を指定する場合は以下の方法
                    //NSDateComponents components = new NSDateComponents();
                    //components.TimeZone = NSTimeZone.DefaultTimeZone;
                    //components.Year = _notifyDate.LocalDateTime.Year;
                    //components.Month = _notifyDate.LocalDateTime.Month;
                    //components.Day = _notifyDate.LocalDateTime.Day;
                    //components.Hour = _notifyDate.LocalDateTime.Hour;
                    //components.Minute = _notifyDate.LocalDateTime.Minute;
                    //components.Second = _notifyDate.LocalDateTime.Second;
                    //var calendarTrigger = UNCalendarNotificationTrigger.CreateTrigger(components, false);

                    var requestID    = "notifyKey";
                    content.UserInfo = NSDictionary.FromObjectAndKey(new NSString("notifyValue"), new NSString("notifyKey"));
                    var request      = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                    UNUserNotificationCenter.Current.Delegate = new LocalNotificationCenterDelegate();

                    // ローカル通知を予約する
                    UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                        if (err != null)
                        {
                            // Do something with error...
                            //LogUtility.OutPutError(err.LocalizedFailureReason + System.Environment.NewLine + err.LocalizedDescription);
                        }
                    });
                    UIApplication.SharedApplication.ApplicationIconBadgeNumber += 1; // アイコン上に表示するバッジの数値
                });
            }
            else    //iOS9まで向け
            {
                UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                    _notification = new UILocalNotification();
                    _notification.Init();
                    _notification.FireDate = NSDate.FromTimeIntervalSinceNow(10); //メッセージを通知する日時
                    _notification.TimeZone = NSTimeZone.DefaultTimeZone;
                    //_notification.RepeatInterval = NSCalendarUnit.Day; // 日々繰り返しする場合
                    _notification.AlertTitle  = title;
                    _notification.AlertBody   = body;
                    _notification.AlertAction = @"Open"; //ダイアログで表示されたときのボタンの文言
                    _notification.UserInfo    = NSDictionary.FromObjectAndKey(new NSString("NotificationValue"), new NSString("NotificationKey"));
                    _notification.SoundName   = UILocalNotification.DefaultSoundName;
                    // アイコン上に表示するバッジの数値
                    UIApplication.SharedApplication.ApplicationIconBadgeNumber += 1;
                    //通知を登録
                    UIApplication.SharedApplication.ScheduleLocalNotification(_notification);
                });
            }
        }
示例#25
0
        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=
                        //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.Sound.IsEmpty())
            {
                content.Sound = UNNotificationSound.GetSound(notification.Sound);
            }

            UNNotificationTrigger trigger = null;

            if (notification.ScheduleDate == null)
            {
                trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(3, false);
            }
            else
            {
                var dt = notification.ScheduleDate.Value.ToLocalTime();
                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);
        }
示例#26
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            btnNotificacionesIntervalo.TouchUpInside += delegate {
                Console.WriteLine("N0rf3n - btnNotificacionesIntervalo - Begin ");

                NSUrl ArchivoGif       = NSUrl.FromFilename("Notificacion.gif");
                var   IdArchivo        = "Not";//identificador del archivo
                var   OpcionesAdjuntar = new UNNotificationAttachmentOptions();
                var   Contenido        = new UNMutableNotificationContent();
                Contenido.Title    = "Nueva Notificacion";
                Contenido.Subtitle = "Suena la campana.Tirin tirin.. ";
                Contenido.Body     = "Notificacion Local";
                Contenido.Sound    = UNNotificationSound.Default;
                Contenido.Badge    = 1;

                NSError error;

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

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

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

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

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

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

                Console.WriteLine("N0rf3n - btnNotificacionesIntervalo - End ");
            };

            btnNotificacionesCalendario.TouchUpInside += delegate {
                Console.WriteLine("N0rf3n - btnNotificacionesCalendario - Begin ");

                NSUrl ArchivoGif       = NSUrl.FromFilename("Notificacion.gif");
                var   IdArchivo        = "Not";//identificador del archivo
                var   OpcionesAdjuntar = new UNNotificationAttachmentOptions();
                var   Contenido        = new UNMutableNotificationContent();
                Contenido.Title    = "Notificacion Calendario";
                Contenido.Subtitle = "Suena la campana.Tirin tirin.. ";
                Contenido.Body     = "Notificacion Local";
                Contenido.Sound    = UNNotificationSound.Default;
                Contenido.Badge    = 1;

                NSError error;

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

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


                //Se onbtiniene los datos de la fecha, hora y demas información del DatePicker.
                DateTime Fecha = (DateTime)Calendario.Date; //Se parcea la fecha del DatePicker
                DateTime Hora  = DateTime.SpecifyKind((DateTime)Calendario.Date, DateTimeKind.Utc).ToLocalTime();

                var ElementoFecha = new NSDateComponents();//Variable para alimentar a la notificacion
                ElementoFecha.Minute   = nint.Parse(Hora.Minute.ToString());
                ElementoFecha.Hour     = nint.Parse(Hora.Hour.ToString());
                ElementoFecha.Month    = nint.Parse(Fecha.Month.ToString());
                ElementoFecha.Year     = nint.Parse(Fecha.Year.ToString());
                ElementoFecha.Day      = nint.Parse(Fecha.Day.ToString());
                ElementoFecha.TimeZone = NSTimeZone.SystemTimeZone;

                Console.WriteLine(string.Format("N0rf3n - {0}io - ElementoFecha :  ", "btnNotificacionesCalendar") + ElementoFecha);


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

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

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

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

                Console.WriteLine("N0rf3n - btnNotificacionesCalendario - End ");
            };

            UNUserNotificationCenter CentrodeNotificacion =
                UNUserNotificationCenter.Current;                                                               //Permite generar categorias

            NSNotificationCenter.DefaultCenter.AddObserver((NSString)                                           //Se debe crear un observador, para que este atento de lo que el usuario esta realizando.
                                                           "NotificacionDeRespuesta", NotificacionDeRespuesta); //la palabra clave será NotificacionDeRespuesta


            btnNotificacionesRespuesta.TouchUpInside += delegate {
                Console.WriteLine("N0rf3n - btnNotificacionesSRespuesta - Begin ");
                Console.WriteLine("N0rf3n - btnTmp - test... ");
                CentrodeNotificacion.Delegate = new Notificacion(); //Es una instancia hacia notificacion.
                Notificacion.Categoria();
                Notificacion.EnviarNotificacion();
                Console.WriteLine("N0rf3n - btnNotificacionesSRespuesta - End ");
            };
        }
示例#27
0
        private void SentNotificationForOverdue(List <Customer> countНotifyInvoiceOverdueCustomers)
        {
            if (countНotifyInvoiceOverdueCustomers.Count > 0)
            {
                //string countНotifyInvoiceOverdueCustomersAsString = JsonConvert.SerializeObject(countНotifyInvoiceOverdueCustomers);

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

                content.Title = "Просрочване";

                List <string> notificationContent = new List <string>();

                foreach (var item in countНotifyInvoiceOverdueCustomers)
                {
                    // Generate a message summary for the body of the notification:

                    string format = "dd.MM.yyyy";
                    string date   = item.EndPayDate.ToString(format);

                    string currentRowContent = ($"Аб. номер: {item.Nomer.ToString()}, {date}" + System.Environment.NewLine);

                    notificationContent.Add(currentRowContent);
                }

                string fullContent = string.Empty;

                foreach (var item in notificationContent)
                {
                    fullContent = fullContent + item;
                }

                content.Body = fullContent;

                content.Sound = UNNotificationSound.Default;


                var notification = new UILocalNotification();
                // Fire trigger in one seconds
                var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);

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

                //Here I set the Delegate to handle the user tapping on notification
                // UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                {
                    if (err != null)
                    {
                        // Report error
                        System.Console.WriteLine("Error: {0}", err);
                    }
                    else
                    {
                        // Report Success
                        System.Console.WriteLine("Notification Scheduled: {0}", request);
                    }
                });
            }
        }
        /// <inheritdoc />
        public async void Show(NotificationRequest notificationRequest)
        {
            UNNotificationTrigger trigger = null;

            try
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0) == false)
                {
                    return;
                }

                if (notificationRequest is null)
                {
                    return;
                }

                var allowed = await NotificationCenter.AskPermissionAsync().ConfigureAwait(false);

                if (allowed == false)
                {
                    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 receivedData = new NSString(notificationRequest.iOS.HideForegroundAlert.ToString());
                userInfoDictionary.SetValueForKey(receivedData, NotificationCenter.ExtraNotificationReceivedIos);

                using var soundData = new NSString(notificationRequest.iOS.PlayForegroundSound.ToString());
                userInfoDictionary.SetValueForKey(soundData, NotificationCenter.ExtraSoundInForegroundIos);

                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);
                }

                var repeats = notificationRequest.Repeats != NotificationRepeat.No;

                if (repeats && notificationRequest.Repeats == NotificationRepeat.TimeInterval &&
                    notificationRequest.NotifyRepeatInterval.HasValue)
                {
                    TimeSpan interval = notificationRequest.NotifyRepeatInterval.Value;

                    trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(interval.TotalSeconds, true);
                }
                else
                {
                    using var notifyTime = GetNsDateComponentsFromDateTime(notificationRequest);
                    trigger = UNCalendarNotificationTrigger.CreateTrigger(notifyTime, repeats);
                }

                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);
            }
            finally
            {
                trigger?.Dispose();
            }
        }
        void PopUpAlmoco(string msg)
        {
            var hrsDeAlmoco = genericController.GetAlmoco();

            if (hrsDeAlmoco.Count == 1)
            {
                var timeAlmoco = hrsDeAlmoco[0].ToString("HH:mm");
                msg = "Iniciado as: " + timeAlmoco + "\n\n" + msg;
            }
            var alert = UIAlertController.Create("Horario de Almoco", msg, UIAlertControllerStyle.Alert);

            alert.AddAction(UIAlertAction.Create("Nao", UIAlertActionStyle.Cancel, (actionCancel) =>
            {
                if (msg.Contains("Gostaria de finalizar o horario de almoco em seu ponto eletronico ?"))
                {
                    Process.GetCurrentProcess().CloseMainWindow();
                }
            }));

            alert.AddAction(UIAlertAction.Create("Sim", UIAlertActionStyle.Default, (actionOK) =>
            {
                if (SetAlmoco())
                {
                    var contentAlmoco = new UNMutableNotificationContent
                    {
                        Title    = "Aviso",
                        Subtitle = "Termino do horario de almoco",
                        Body     = "10 Minutos restantes para o fim do horario de almoco"
                    };
                    var notificationTimerAlmoco = UNNotificationRequest.FromIdentifier(requestID, contentAlmoco,
                                                                                       UNTimeIntervalNotificationTrigger.CreateTrigger(60 * 50, false));
                    var contentAlmocoInicio = new UNMutableNotificationContent
                    {
                        Title    = "Aviso",
                        Subtitle = "Inicio do horario de almoco",
                        Body     = "Iniciado as: " + DateTime.Now.ToString("HH:mm")
                    };
                    var notificationInicioAlmoco = UNNotificationRequest.FromIdentifier(requestIDInicio, contentAlmocoInicio,
                                                                                        UNTimeIntervalNotificationTrigger.CreateTrigger(60 * 50, false));

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

                    Process.GetCurrentProcess().CloseMainWindow();
                }
            }));
            alert.View.TintColor = UIColor.FromRGB(10, 88, 90);
            PresentViewController(alert, true, null);
        }
示例#30
0
        private void SentNoficationForNewInovoice(List <Customer> countNewНotifyNewInvoiceCustomers)
        {
            if (countNewНotifyNewInvoiceCustomers.Count > 0)
            {
                // Create content
                var content = new UNMutableNotificationContent();

                content.Title = "Нова фактура";

                List <string> notificationContent = new List <string>();

                foreach (var item in countNewНotifyNewInvoiceCustomers)
                {
                    // Generate a message summary for the body of the notification:

                    string money = item.MoneyToPay.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("bg-BG"));

                    string currentRowContent = ($"Аб. номер: {item.Nomer.ToString()}, {money}" + Environment.NewLine);

                    notificationContent.Add(currentRowContent);

                    // bulideer.SetContentText($"Аб. номер: {item.Nomer.ToString()}, {money}");
                }

                string fullContent = string.Empty;

                foreach (var item in notificationContent)
                {
                    fullContent = fullContent + item;
                }

                content.Body = fullContent;

                content.Sound = UNNotificationSound.Default;


                var notification = new UILocalNotification();
                // Fire trigger in one seconds
                var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false); //////////////////false

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

                //Here I set the Delegate to handle the user tapping on notification
                // UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                {
                    if (err != null)
                    {
                        // Report error
                        System.Console.WriteLine("Error: {0}", err);
                    }
                    else
                    {
                        // Report Success
                        System.Console.WriteLine("Notification Scheduled: {0}", request);
                    }
                });
            }
        }