Xamarin iOS Rich Push Notification Проблема
Я пытаюсь реализовать мультимедийные / расширенные / расширенные уведомления в IOS. У меня есть iPhone 6, 6 и 7. Изображение, которое я отправляю в полезной нагрузке, появляется в расширенном уведомлении 6, но не 6 или 7. Кажется, что код просто останавливается на CreateDownloadTask (я проверил, что могу изменить основной текст непосредственно перед этой строкой кода, но не могу после). У меня даже была более простая версия этого использования NSData.FromUrl(url), но код "ломается" в этой строке. Странно думать, что на самом деле он не ломается, он отображает текст для элемента Body, который был первоначально помещен. Даже попытка поймать не захватывает ошибку. FYI..категория есть для пользовательского интерфейса, который я создаю. Не могу понять, почему он работает правильно только на iphone 6 (все телефоны на 10.2.x или выше)
полезная нагрузка: {"aps": {"alert": {"title": "title", "subtitle": "subtitle", "body": "body"}, "category": "pushWithImage", "mutable- content ": 1}," pushImage ":" https://ewcweb.azurewebsites.net/media/boldlythumb.png"}
Я не могу отправить проект, но ниже приведен код расширения сервиса:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Foundation;
using SDWebImage;
using UIKit;
using UserNotifications;
namespace notifications
{
[Register ("NotificationService")]
public class NotificationService : UNNotificationServiceExtension
{
UNMutableNotificationContent BestAttemptContent { get; set; }
public Action ContentHandler { get; set; }
const string ATTACHMENT_IMAGE_KEY = "pushImage";
const string ATTACHMENT_FILE_NAME = "-attachment-image.";
protected NotificationService (IntPtr handle) : base (handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public async Task<byte[]> LoadImage (string imageUrl)
{
var httpClient = new HttpClient ();
var contentsTask = await httpClient.GetByteArrayAsync (imageUrl);
return contentsTask;
}
public override void DidReceiveNotificationRequest (UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
string imageURL = null;
ContentHandler = contentHandler;
BestAttemptContent = request.Content.MutableCopy () as UNMutableNotificationContent;
if (BestAttemptContent != null) {
if (BestAttemptContent.UserInfo.ContainsKey (new NSString (ATTACHMENT_IMAGE_KEY))) {
imageURL = BestAttemptContent.UserInfo.ValueForKey (new NSString (ATTACHMENT_IMAGE_KEY)).ToString ();
}
if (imageURL == null) {
ContentHandler (BestAttemptContent);
return;
}
var url = new NSUrl (imageURL.ToString ());
NSError err = null;
var task = NSUrlSession.SharedSession.CreateDownloadTask ( new NSMutableUrlRequest (url),(tempfile, response, error) => {
if (error != null)
{
ContentHandler (BestAttemptContent);
return;
}
if (tempfile == null)
{
ContentHandler (BestAttemptContent);
return;
}
var cache = NSSearchPath.GetDirectories (NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true);
var cachesFolder = cache [0];
var guid = NSProcessInfo.ProcessInfo.GloballyUniqueString;
var fileName = guid + ".png";
var cacheFile = cachesFolder + "/" + fileName;
var attachmentURL = NSUrl.CreateFileUrl (cacheFile, false, null);
NSFileManager.DefaultManager.Move(tempfile, attachmentURL, out err);
if (err != null)
{
ContentHandler (BestAttemptContent);
return;
}
// Create attachment;
var attachmentID = "image";
var options = new UNNotificationAttachmentOptions ();
var attachment = UNNotificationAttachment.FromIdentifier (attachmentID, attachmentURL, options, out err);
BestAttemptContent.Attachments = new UNNotificationAttachment [] { attachment };
BestAttemptContent.Title = BestAttemptContent.Title;
BestAttemptContent.Body = BestAttemptContent.Body;
BestAttemptContent.CategoryIdentifier = BestAttemptContent.CategoryIdentifier;
BestAttemptContent.Subtitle = BestAttemptContent.Subtitle;
//Display notification
ContentHandler (BestAttemptContent);
});
task.Resume ();
} else {
// Display notification
ContentHandler (BestAttemptContent);
}
}
public override void TimeWillExpire ()
{
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
ContentHandler (BestAttemptContent);
}
}
}