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

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

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

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

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

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

            ContentHandler(BestAttemptContent);
        }
Example #2
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 ");
        }
Example #3
0
        private static UNNotificationAttachment CreateImageAttachment(UNNotificationRequest request)
        {
            var filePath   = DownloadAttachedImageFile(request);
            var options    = new UNNotificationAttachmentOptions();
            var fileUrl    = NSUrl.CreateFileUrl(filePath, false, null);
            var attachment = UNNotificationAttachment.FromIdentifier("image", fileUrl, options, out var error);

            return(error == null ? attachment : throw new Exception(error.LocalizedDescription));
        }
        /*
         * Link up image with notification
         */
        private UNMutableNotificationContent AddImageAttachment(UNMutableNotificationContent content, string image)
        {
            var     localUrl = "file://" + NSBundle.MainBundle.PathForResource(image, "png");
            NSUrl   url      = NSUrl.FromString(localUrl);
            var     options  = new UNNotificationAttachmentOptions();
            NSError error;
            var     attachment = UNNotificationAttachment.FromIdentifier("image", url, options, out error);

            content.Attachments = new UNNotificationAttachment[] { attachment };

            return(content);
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="notificationImage"></param>
        /// <returns></returns>
        protected virtual async Task <UNNotificationAttachment> GetNativeImage(NotificationImage notificationImage)
        {
            if (notificationImage is null || notificationImage.HasValue == false)
            {
                return(null);
            }

            NSUrl imageAttachment = null;

            if (string.IsNullOrWhiteSpace(notificationImage.ResourceName) == false)
            {
                imageAttachment = NSBundle.MainBundle.GetUrlForResource(Path.GetFileNameWithoutExtension(notificationImage.ResourceName), Path.GetExtension(notificationImage.ResourceName));
            }
            if (string.IsNullOrWhiteSpace(notificationImage.FilePath) == false)
            {
                if (File.Exists(notificationImage.FilePath))
                {
                    imageAttachment = NSUrl.CreateFileUrl(notificationImage.FilePath, false, null);
                }
            }
            if (notificationImage.Binary != null && notificationImage.Binary.Length > 0)
            {
                using (var stream = new MemoryStream(notificationImage.Binary))
                {
                    var image          = Image.FromStream(stream);
                    var imageExtension = image.RawFormat.ToString();

                    var cache = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory,
                                                            NSSearchPathDomain.User);
                    var cachesFolder = cache[0];
                    var cacheFile    = $"{cachesFolder}{NSProcessInfo.ProcessInfo.GloballyUniqueString}.{imageExtension}";

                    if (File.Exists(cacheFile))
                    {
                        File.Delete(cacheFile);
                    }

                    await File.WriteAllBytesAsync(cacheFile, notificationImage.Binary);

                    imageAttachment = NSUrl.CreateFileUrl(cacheFile, false, null);
                }
            }

            if (imageAttachment is null)
            {
                return(null);
            }

            var options = new UNNotificationAttachmentOptions();

            return(UNNotificationAttachment.FromIdentifier("image", imageAttachment, options, out _));
        }
Example #6
0
        UNNotificationAttachment CreateAttachment(string id, NSUrl url, string?typeHint = null)
        {
            var options = new UNNotificationAttachmentOptions()
            {
                TypeHint = typeHint
            };
            var attachment = UNNotificationAttachment.FromIdentifier(id, url, options, out var error);

            if (error != null)
            {
                throw new InvalidOperationException("got error while creating attachment: " + error.ToString());
            }
            if (attachment == null)
            {
                throw new InvalidOperationException("cant create attachment");
            }
            return(attachment);
        }
        public static void Sendlocalnotification()
        {
            //Click Sendnotification button then badgenumber will add
            UIApplication.SharedApplication.ApplicationIconBadgeNumber += 1;
            Console.WriteLine("Sendlocalnotification");

            //If you want to add another picture.Make sure right click your image: Build Action -> BundleResource
            //Warning!!!if you don't add "file:///" it will occur error like invalid attachment file URL......
            //URL detail : https://developer.apple.com/reference/foundation/nsurl#//apple_ref/occ/clm/NSURL/fileURLWithPath:isDirectory:
            var localURL = "file:///" + NSBundle.MainBundle.PathForResource("RUN", "gif");

            NSUrl url = NSUrl.FromString(localURL);


            var     attachmentID = "gif";
            var     options      = new UNNotificationAttachmentOptions();
            NSError error;
            var     attachment = UNNotificationAttachment.FromIdentifier(attachmentID, url, options, out error);


            var content = new UNMutableNotificationContent();

            content.Attachments        = new UNNotificationAttachment[] { attachment };
            content.Title              = "Good Morning ~";
            content.Subtitle           = "Pull this notification ";
            content.Body               = "reply some message-BY Ann";
            content.CategoryIdentifier = "message";

            var trigger1 = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);

            var requestID = "messageRequest";
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger1);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    Console.Write("Notification Error");
                }
            });
        }
Example #8
0
        public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action <UNNotificationContent> contentHandler)
        {
            // Get file URL
            var attachementPath = request.Content.UserInfo.ObjectForKey(new NSString("my-attachment"));
            var url             = new NSUrl(attachementPath.ToString());

            // Download the file
            var localURL = new NSUrl("PathToLocalCopy");

            // Create attachment
            var     attachmentID = "image";
            var     options      = new UNNotificationAttachmentOptions();
            NSError err;
            var     attachment = UNNotificationAttachment.FromIdentifier(attachmentID, localURL, options, out err);

            // Modify contents
            var content = request.Content.MutableCopy() as UNMutableNotificationContent;

            content.Attachments = new UNNotificationAttachment[] { attachment };

            // Display notification
            contentHandler(content);
        }
Example #9
0
        private void AddingPhotoToNotification(RestaurantMO restaurantMO, UNMutableNotificationContent content)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var suggestedRestaurantImage = Path.Combine(documents, "suggested-restaurant.jpg");

            var image = restaurantMO.GetImage();

            if (image != null)
            {
                try
                {
                    NSError err = null;
                    image.AsJPEG(1)?.Save(suggestedRestaurantImage, false, out err);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                try
                {
                    NSError error;
                    UNNotificationAttachmentOptions attachmentOptions = new UNNotificationAttachmentOptions();
                    var finalImage      = "file:///" + suggestedRestaurantImage;
                    var restaurantImage = UNNotificationAttachment.FromIdentifier("restaurantImage", new NSUrl(finalImage), attachmentOptions, out error);
                    if (restaurantImage != null)
                    {
                        content.Attachments = new[] { restaurantImage };
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Example #10
0
 public static UNNotificationAttachment FromIdentifier(string identifier, NSUrl url, UNNotificationAttachmentOptions attachmentOptions, out NSError error)
 {
     return(FromIdentifier(identifier, url, attachmentOptions?.Dictionary, out error));
 }
Example #11
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 ");
            };
        }
Example #12
0
        public void ApplicationReceivedRemoteMessage(RemoteMessage remoteMessage)
        {
            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        = (remoteMessage.AppData[new NSString("header")] as NSString).ToString();
                string message      = (remoteMessage.AppData[new NSString("message")] as NSString).ToString();
                string imageURL     = (remoteMessage.AppData[new NSString("image")] as NSString).ToString();
                var    notificaiton = new UNMutableNotificationContent();

                notificaiton.Title = title;
                notificaiton.Body  = App.HtmlToPlainText(message);
                if (!string.IsNullOrEmpty(imageURL) && !imageURL.ToLower().Contains("pdf"))
                {
                    var url       = new Uri(imageURL.ToString());
                    var webClient = new WebClient();
                    webClient.DownloadDataAsync(url);
                    webClient.DownloadDataCompleted += (s, e) =>
                    {
                        var    bytes         = e.Result; // get the downloaded data
                        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                        string localFilename = "downloaded.png";
                        string localPath     = Path.Combine(documentsPath, localFilename);
                        File.WriteAllBytes(localPath, bytes);
                        var     localUrl     = NSUrl.FromString("file:///" + localPath);
                        var     attachmentID = "image";
                        var     options      = new UNNotificationAttachmentOptions();
                        NSError _error;
                        var     attachment = UNNotificationAttachment.FromIdentifier(attachmentID, localUrl, options, out _error);
                        if (_error == null)
                        {
                            notificaiton.Attachments = new UNNotificationAttachment[] { attachment };
                            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, (error) =>
                            {
                                if (error != null)
                                {
                                }
                            });
                        }
                        else
                        {
                            Debug.Write(_error.ToString());
                        }
                    };

                    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());
                    }
                }
                else
                {
                    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());
                    }
                }
            }
        }