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);
        }
Пример #2
0
        void ScheduleNotification()
        {
            // Create content
            var content = new UNMutableNotificationContent();

            content.Title              = "Title";
            content.Subtitle           = "Subtitle";
            content.Body               = "Body";
            content.Badge              = 1;
            content.CategoryIdentifier = categoryID;
            content.Sound              = UNNotificationSound.Default;

            // Fire trigger in one seconds
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

            var requestID = "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);
                }
            });
        }
        public async static Task <bool> Show(string title, string body, bool playSound = false, Dictionary <string, string> parameters = null)
        {
            try
            {
                if (!await Permission.LocalNotification.IsGranted())
                {
                    await Alert.Show("Permission was not granted to show local notifications.");

                    return(false);
                }

                if (OS.IsAtLeastiOS(10))
                {
                    var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(.1, repeats: false);
                    ShowUserNotification(title, body, 0, trigger, playSound, parameters);
                    return(true);
                }
                else
                {
                    return(await Schedule(title, body, DateTime.Now, 0, parameters : parameters));
                }
            }
            catch (Exception ex)
            {
                Log.For(typeof(LocalNotification)).Error(ex);
                return(false);
            }
        }
Пример #4
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)
            {
            }
        }
Пример #5
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);
                }
            });
        }
Пример #6
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...
                }
            });
        }
Пример #7
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 ");
        }
Пример #8
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);
        }
Пример #9
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);
                        }
                    });
                }
            });
        }
Пример #10
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;
        }
Пример #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...");
                }
            });
        }
Пример #12
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}");
                }
            });
        }
        public int BildirimiZamanla(string bildirimBasligi, string bildirimMesaji)
        {
            // EARLY OUT: app doesn't have permissions
            if (!bildirimIzniVarMi)
            {
                return(-1);
            }

            mesajID++;

            var bildirimIcerigi = new UNMutableNotificationContent()
            {
                Title    = bildirimBasligi,
                Subtitle = "",
                Body     = bildirimMesaji,
                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 istek = UNNotificationRequest.FromIdentifier(mesajID.ToString(), bildirimIcerigi, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(istek, (hata) =>
            {
                if (hata != null)
                {
                    throw new Exception($"Bildirim başarısız oldu: {hata}");
                }
            });

            return(mesajID);
        }
Пример #14
0
 public static void PushNotification(object s, EventArgs e)
 {
     if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
     {
         var notificaiton = new UNMutableNotificationContent();
         notificaiton.Title = App.lpushItem.title;
         notificaiton.Body  = App.lpushItem.message;
         notificaiton.Badge = 1;
         var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
         var requestID = "MEI_LocalNotification";
         var request   = UNNotificationRequest.FromIdentifier(requestID, notificaiton, trigger);
         UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
         {
             if (err != null)
             {
             }
         });
     }
     else
     {
         UILocalNotification notification = new UILocalNotification();
         notification.AlertAction = App.lpushItem.title;
         notification.AlertBody   = App.lpushItem.message;
         UIApplication.SharedApplication.ScheduleLocalNotification(notification);
     }
     //UILocalNotification notification = new UILocalNotification();
     //notification.AlertAction = App.lpushItem.title;
     //notification.AlertBody = App.lpushItem.message;
     //notification.FireDate = NSDate.FromTimeIntervalSinceNow(0);
     //notification.ApplicationIconBadgeNumber = 1;
     //notification.SoundName = UILocalNotification.DefaultSoundName;
     //UIApplication.SharedApplication.ScheduleLocalNotification(notification);
 }
Пример #15
0
        public void ShowNotification(string title, string subtitle, string body)
        {
            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
            {
                if (!approved)
                {
                    return;
                }

                var content = new UNMutableNotificationContent()
                {
                    Title    = title,
                    Subtitle = subtitle,
                    Body     = body
                };

                var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.25, false);
                var request = UNNotificationRequest.FromIdentifier(Guid.NewGuid().ToString(), content, trigger);
                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                {
                    if (err != null)
                    {
                        throw new System.Exception($"Failed to schedule notification: {err}");
                    }
                });
            });
        }
Пример #16
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);
        }
        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);
        }
Пример #18
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++);
 }
        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);
            }
        }
Пример #20
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");
                            }
                        });
                    }
                });
            });
        }
Пример #21
0
        private void SentNotificationForReading(List <Customer> countНotifyReadingustomers)
        {
            if (countНotifyReadingustomers.Count > 0)
            {
                var content = new UNMutableNotificationContent();

                // Set the title and text of the notification:
                content.Title = "Ден на отчитане";

                List <string> notificationContent = new List <string>();
                // content.Body = string.Empty;

                foreach (var item in countНotifyReadingustomers)
                {
                    // Generate a message summary for the body of the notification:
                    string format = "dd.MM.yyyy";
                    string date   = item.StartReportDate.ToString(format);

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

                    notificationContent.Add(currentRowContent);
                    //   content.Body = ($"Аб. номер: {item.Nomer.ToString()}, {date}" + System.Environment.NewLine);
                }
                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 = "reading";   ///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);
                    }
                });
            }
        }
Пример #22
0
        public int ExecAPIs()
        {
            if (!itsRunning)
            {
                itsRunning = true;
                PopulateSync();
                try
                {
                    controller.ExecRestApis();
                }
                //O XGH só existe quando é encontrado. Se ta funcionando NAO RELA A MAO.
                catch (InvalidLoginException invalid)
                {
                    try
                    {
                        InvokeOnMainThread(delegate
                        {
                            model.db.RemoveUser(invalid.userID);
                        });
                    }
                    catch (InvalidOperationException)
                    {
                        return(-99);
                    }
                }
#if !DEBUG
                catch (Exception ex)
                {
                    MetricsManager.TrackEvent("SyncDataFail");
                    MetricsManager.TrackEvent(ex.Message);
                }
#endif
                var NewPdvs = new List <string>();
                InvokeOnMainThread(delegate
                {
                    NewPdvs = controller.GetNovosPdvsNotification();
                    if (NewPdvs.Count > 0)
                    {
                        var content = new UNMutableNotificationContent
                        {
                            Title    = "Novos PDVs",
                            Subtitle = "Roteiro Atualizado",
                            Body     = "Existem " + NewPdvs.Count + " novos PDVs cadastrados",
                            Badge    = NewPdvs.Count
                        };
                        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

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

                        UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { });
                    }
                });
                itsRunning = false;
                return(NewPdvs.Count);
            }
            return(0);
        }
Пример #23
0
        public static void OnFinishLoading(TorrentManager manager, TorrentStateChangedEventArgs args)
        {
            var newState = Utils.GetManagerTorrentState(manager);

            Console.WriteLine(manager.Torrent.Name + " State chaged: " + newState);
            if (manager.State == TorrentState.Seeding && !manager.allowSeeding)
            {
                Console.WriteLine("Stopping 2");
                manager.Stop();
            }
            else if (manager.State == TorrentState.Downloading &&
                     !manager.allowSeeding)
            {
                long size       = 0;
                long downloaded = 0;

                if (manager.Torrent != null)
                {
                    foreach (var f in manager.Torrent.Files)
                    {
                        if (f.Priority != Priority.DoNotDownload)
                        {
                            size       += f.Length;
                            downloaded += f.BytesDownloaded;
                        }
                    }
                }

                if (downloaded >= size && manager.HasMetadata && manager.State != TorrentState.Hashing)
                {
                    Console.WriteLine("Stopping 3");
                    manager.Stop();
                }
            }
            else if (newState == TorrentState.Finished || newState == TorrentState.Seeding)
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    var content = new UNMutableNotificationContent();
                    content.Title = "Download finished";
                    content.Body  = manager.Torrent.Name + " finished downloading";
                    content.Sound = UNNotificationSound.Default;

                    var date       = DateTime.Now;
                    var trigger    = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
                    var identifier = manager.Torrent.Name;
                    var request    = UNNotificationRequest.FromIdentifier(identifier, content, trigger);

                    UNUserNotificationCenter.Current.AddNotificationRequest(request, null);
                }

                Background.CheckToStopBackground();
            }
            foreach (var action in Manager.Singletone.managerStateChanged)
            {
                action?.Invoke();
            }
        }
        private void OnSendAlert(object sender, EventArgs e)
        {
            // Code following the suggestions made in this Xamarin Forms Forum thread
            //   https://forums.xamarin.com/discussion/comment/372220#Comment_372220

            //Get current notification settings
            UNUserNotificationCenter.Current.GetNotificationSettings((settings) =>
            {
                alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);

                InvokeOnMainThread(() =>
                {
                    swtAlertsAllowed.On = alertsAllowed;

                    if (alertsAllowed)
                    {
                        // Create the content of the Local Notification
                        UNMutableNotificationContent content = new UNMutableNotificationContent();
                        content.Title    = txtNotificationTitle.Text;
                        content.Subtitle = txtNotificationSubTitle.Text;
                        content.Body     = $"{txtNotificationBody.Text} with Notification Count of {alertCount}";
                        content.Badge    = 1;

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

                        string requestID = $"SampleRequest{alertCount}";
                        UNNotificationRequest request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                        lblAlertStatus.Text = "Sending Alert...";

                        UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
                        {
                            if (err != null)
                            {
                                InvokeOnMainThread(() =>
                                {
                                    lblAlertStatus.Text = "Error: Alert NOT Sent";
                                });
                            }
                            else
                            {
                                InvokeOnMainThread(() =>
                                {
                                    lblAlertStatus.Text = $"Alert (ID: {requestID}) Sent will appear after 15 seconds";
                                });
                            }
                        });

                        alertCount++;
                    }
                    else
                    {
                        lblAlertStatus.Text = "Alerts NOT Allowed";
                    }
                });
            });
        }
Пример #25
0
        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);
                }
            });
        }
Пример #26
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);
            }

            var dt      = notification.ScheduleDate ?? DateTime.Now;
            var trigger = notification.ScheduleDate == null
                ? (UNNotificationTrigger)UNTimeIntervalNotificationTrigger.CreateTrigger(3, false)
                : 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);
        }
Пример #27
0
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action <UNNotificationPresentationOptions> completionHandler)
        {
            try {
                if (!(notification.Request.Content.UserInfo.ObjectForKey(new NSString("aps")) is NSDictionary aps))
                {
                    return;
                }

                if (notification.Request.Identifier == REBUILD_NOTIFICATION_KEY)
                {
                    completionHandler(UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Alert);
                }
                else
                {
                    NSData jsonData   = NSJsonSerialization.Serialize(aps, 0, out NSError error);
                    string jsonResult = jsonData.ToString();
                    bool   forMe      = default(bool);

                    NotificationMessage notificationMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <NotificationMessage>(jsonResult);
                    forMe = BaseSingleton <GlobalSetting> .Instance.UserProfile?.NetId == notificationMessage.UserNetId;

                    if (forMe)
                    {
                        // Rebuild notification
                        var content = new UNMutableNotificationContent {
                            Sound    = UNNotificationSound.Default,
                            Title    = "Запит по фізичній особі",
                            Body     = "Оброблено",
                            UserInfo = notification.Request.Content.UserInfo
                        };

                        // New trigger time
                        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

                        // ID of Notification to be updated
                        var requestID = REBUILD_NOTIFICATION_KEY;
                        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...
                                Debugger.Break();
                            }
                        });
                    }
                }
            } catch (Exception ex) {
                string message = ex.Message;
                Debugger.Break();
            }
        }
Пример #28
0
 public void Show(string title, string body, int id = 0)
 {
     if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
     {
         var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(.1, false);
         ShowUserNotification(title, body, id, trigger);
     }
     else
     {
         Show(title, body, id, DateTime.Now);
     }
 }
Пример #29
0
        public int ScheduleNotification(string title, string subtitle, string message, double duration)
        {
            // EARLY OUT: app doesn't have permissions
            if (!hasNotificationsPermission)
            {
                return(-1);
            }

            messageId++;

            //
            // Using C# objects, strings and ints, produces
            // a dictionary with 2 NSString keys, "key1" and "key2"
            // and two NSNumbers with the values 1 and 2
            //
            var key1   = new NSString("routineNum");
            var value1 = new NSNumber(Int32.Parse(subtitle.Substring(0, 1)));
            var key2   = new NSString("routineId");
            var value2 = new NSString(subtitle.Substring(1, 20));

            var userInfo = new NSDictionary(key1, value1, key2, value2);

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

            Console.WriteLine("here");

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

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

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    Console.WriteLine($"Failed to schedule notification: {err}");
                }
                else
                {
                    Console.WriteLine($"notification: {request} made to notify in {duration} seconds.");
                }
            });

            return(messageId);
        }
Пример #30
0
        static void ExecAPIs(bool isToUpdateImage)
        {
            itsRunning = true;
            PopulateSync();
            try
            {
                controller.ExecRestApis();
                if (isToUpdateImage)
                {
                    UploadImages();
                }
            }
            catch (InvalidLoginException invalid)
            {
                try
                {
                    model.db.RemoveUser(invalid.userID);
                }
                catch (InvalidOperationException)
                {
                    Process.GetCurrentProcess().CloseMainWindow();
                }
            }

            catch (Exception ex)
            {
#if !DEBUG
                MetricsManager.TrackEvent("SyncDataFail");
                MetricsManager.TrackEvent(ex.Message);
#endif
#if DEBUG
                throw ex;
#endif
            }
            var NewPdvs = new List <string>();
            NewPdvs = controller.GetNovosPdvsNotification();
            if (NewPdvs.Count > 0)
            {
                var content = new UNMutableNotificationContent
                {
                    Title    = "Novos PDVs",
                    Subtitle = "Roteiro Atualizado",
                    Body     = "Existem " + NewPdvs.Count + " novos PDVs cadastrados",
                    Badge    = NewPdvs.Count
                };
                var trigger   = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
                var requestID = "newPdvs";
                var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
                UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => { });
            }
            itsRunning = false;
        }