//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 "); }
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); }
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); }
/// <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 _)); }
public void ThrowsExceptionOnUnknownRouteForSingle(object route) { // prepare var attachment = UNNotificationAttachment.FromIdentifier( Guid.NewGuid().ToString(), NSUrl.FromFilename("filename"), new UNNotificationAttachmentOptions(), out var error); var router = new IOsImageRouter(); var mock = new Mock <IPlatformSpecificExtension>(); var ims = new SealedToastImageSource(attachment); // act && verify Assert.Throws <InvalidOperationException>(() => router.Configure(mock.Object, ims, (Router.Route)route)); }
public void ConfigureSingle(object route) { // prepare var attachment = UNNotificationAttachment.FromIdentifier( Guid.NewGuid().ToString(), NSUrl.FromFilename("filename"), new UNNotificationAttachmentOptions(), out var error); var router = new IOsImageRouter(); var mock = new Mock <IPlatformSpecificExtension>(); ToastImageSource ims = new SealedToastImageSource(attachment); // act router.Configure(mock.Object, ims, (Router.Route)route); // verify mock.Assert(_ => _.AddAttachment(attachment)); }
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 void AddAttachment() { // prepare var attachment = UNNotificationAttachment.FromIdentifier( Guid.NewGuid().ToString(), NSUrl.FromFilename("filename"), new UNNotificationAttachmentOptions(), out var error); var mock = new Mock <IIosNotificationExtension>(); var extension = mock.Object; ToastImageSource ims = new SealedToastImageSource(attachment); // act extension.AddAttachment(ims); // verify mock.Assert(_ => _.Add(ims, Router.Route.IosSingleAttachment)); }
public void ConfigureMultiple(object route) { // prepare var attachment = UNNotificationAttachment.FromIdentifier( Guid.NewGuid().ToString(), NSUrl.FromFilename("filename"), new UNNotificationAttachmentOptions(), out var error); var router = new IOsImageRouter(); var mock = new Mock <IPlatformSpecificExtension>(); ToastImageSource ims = new SealedToastImageSource(attachment); var many = Enumerable.Repeat(ims, 10); // act router.Configure(mock.Object, many, (Router.Route)route); // verify mock.Assert(_ => _.AddAttachments(The <IEnumerable <UNNotificationAttachment> > .Is(e => e.All(i => i == 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"); } }); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { var identifier = new NSUuid().ToString(); var attachmentUrl = new NSUrl(downloadTask.OriginalRequest.Url.LastPathComponent, NSFileManager.DefaultManager.GetTemporaryDirectory()); NSFileManager.DefaultManager.Copy(location, attachmentUrl, out NSError error); if (error != null) { Deliver(); return; } var attachment = UNNotificationAttachment.FromIdentifier(identifier, attachmentUrl, new NSDictionary(), out error); if (error != null) { Deliver(); return; } BestAttemptContent.Attachments = new UNNotificationAttachment[] { attachment }; Deliver(); }
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); }
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); } } }
private async Task <UNMutableNotificationContent> EnrichNotificationContentAsync(UNMutableNotificationContent content, NotificationDto notification) { if (!string.IsNullOrWhiteSpace(notification.Subject)) { content.Title = notification.Subject; } if (!string.IsNullOrWhiteSpace(notification.Body)) { content.Body = notification.Body; } string image = string.IsNullOrWhiteSpace(notification.ImageLarge) ? notification.ImageSmall : notification.ImageLarge; if (!string.IsNullOrWhiteSpace(image)) { var imagePath = await GetImageAsync(image); if (!string.IsNullOrWhiteSpace(imagePath)) { var uniqueName = $"{Guid.NewGuid()}{Path.GetExtension(imagePath)}"; var attachementUrl = new NSUrl(uniqueName, NSFileManager.DefaultManager.GetTemporaryDirectory()); NSFileManager.DefaultManager.Copy(NSUrl.FromFilename(imagePath), attachementUrl, out var error); if (error != null) { Log.Error(error.LocalizedDescription); } var attachement = UNNotificationAttachment.FromIdentifier( Constants.ImageLargeKey, attachementUrl, new UNNotificationAttachmentOptions(), out error); if (error == null) { content.Attachments = new UNNotificationAttachment[] { attachement }; } else { Log.Error(error.LocalizedDescription); } } } var actions = new List <UNNotificationAction>(); if (!string.IsNullOrWhiteSpace(notification.ConfirmUrl) && !string.IsNullOrWhiteSpace(notification.ConfirmText) && !notification.IsConfirmed) { var confirmAction = UNNotificationAction.FromIdentifier( Constants.ConfirmAction, notification.ConfirmText, UNNotificationActionOptions.Foreground); actions.Add(confirmAction); } if (!string.IsNullOrWhiteSpace(notification.LinkUrl) && !string.IsNullOrWhiteSpace(notification.LinkText)) { var linkAction = UNNotificationAction.FromIdentifier( Constants.LinkAction, notification.LinkText, UNNotificationActionOptions.Foreground); actions.Add(linkAction); } if (actions.Any()) { var categoryId = Guid.NewGuid().ToString(); var newCategory = UNNotificationCategory.FromIdentifier( categoryId, actions.ToArray(), new string[] { }, UNNotificationCategoryOptions.None); var categories = new List <UNNotificationCategory>(); var allCategories = await UNUserNotificationCenter.Current.GetNotificationCategoriesAsync(); if (allCategories != null) { foreach (UNNotificationCategory category in allCategories) { if (category.Identifier != categoryId) { categories.Add(category); } } categories.Add(newCategory); } else { categories.Add(newCategory); } UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories.ToArray())); // without this call action buttons won't be added or updated _ = await UNUserNotificationCenter.Current.GetNotificationCategoriesAsync(); content.CategoryIdentifier = categoryId; } if (content.Sound == null) { content.Sound = UNNotificationSound.Default; } notificationHandler?.OnBuildNotification(content, notification); return(content); }
public SealedToastImageSource(UNNotificationAttachment attachment) : base(attachment) { }
/// <summary> /// Initializes a new instance of the <see cref="ToastImageSource"/> class. /// </summary> protected internal ToastImageSource(UNNotificationAttachment attachment) => Attachment = attachment;
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()); } } } }
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 "); }; }