Xamarin.iOS Невозможно отобразить фотографию в Push-уведомлении - PullRequest
0 голосов
/ 29 января 2019

У меня есть расширение службы уведомлений и группа приложений.Я сохраняю фотографию с камеры в проекте PCL и копирую ее в контейнер группы приложений (общая папка).

В расширении службы уведомлений я пытаюсь загрузить фотографию из контейнера группы приложений и прикрепить ее к уведомлению, но она просто не отображается в уведомлении.

Я также не могу отладить службуРасширение, чтобы увидеть, что происходит.Насколько я знаю, в настоящее время это невозможно в Хамарине, если кто-то не может исправить меня, пожалуйста.

Вот код:

1.в моем PCL я сохраняюфотография в AppGroup при нажатии кнопки сохранения:

 private void ButtonSavePhoto_Clicked(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(photoFilePath))
                {
                    Preferences.Set(AppConstants.CUSTOM_PICTURE_FILE_PATH, photoFilePath);
                    Preferences.Set(AppConstants.CUSTOM_PHOTO_SET_KEY, true);

                    if (Device.RuntimePlatform == Device.iOS)
                    {

                        bool copiedSuccessfully = DependencyService.Get<IPhotoService>().CopiedFileToAppGroupContainer(photoFilePath);

                        if (copiedSuccessfully)
                        {
                            var customPhotoDestPath = DependencyService.Get<IPhotoService>().GetAppContainerCustomPhotoFilePath();

                            // save the path of the custom photo in the AppGroup container to pass to Notif Extension Service
                            DependencyService.Get<IGroupUserPrefs>().SetStringValueForKey("imageAbsoluteString", customPhotoDestPath);

                            // condition whether to use custom photo in push notification
                            DependencyService.Get<IGroupUserPrefs>().SetBoolValueForKey("isCustomPhotoSet", true);
                        }
                    }

                    buttonSavePhoto.IsEnabled = false;
                }         
            }

2. в моем проекте iOS внедрение зависимостей вызывает этот метод при нажатии кнопки сохранения:

    public bool CopiedFileToAppGroupContainer(string filePath)
    {
                bool success = false;

                string suiteName = "group.com.company.appName";
                var appGroupContainerUrl = NSFileManager.DefaultManager.GetContainerUrl(suiteName);

                var appGroupContainerPath = appGroupContainerUrl.Path;

                var directoryNameInAppGroupContainer = Path.Combine(appGroupContainerPath, "Pictures");

                var filenameDestPath = Path.Combine(directoryNameInAppGroupContainer, AppConstants.CUSTOM_PHOTO_FILENAME);

                try
                {
                    Directory.CreateDirectory(directoryNameInAppGroupContainer);

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

                    File.Copy(filePath, filenameDestPath);
                    success = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                return success;
            }

Теперь путь к фотографии в контейнере группы приложений:

/ private / var / mobile / Containers / Shared / AppGroup / 12F209B9-05E9-470C-9C9F-AA959D940302 /Pictures / customphoto.jpg

3. Наконец, в расширении службы уведомлений я пытаюсь прикрепить фотографию к push-уведомлению:

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

            string imgPath;
            NSUrl imgUrl;

            string notificationBody = BestAttemptContent.Body;
            string notifBodyInfo = "unknown";

            string suiteName = "group.com.company.appname";  

            NSUserDefaults groupUserDefaults = new NSUserDefaults(suiteName, NSUserDefaultsType.SuiteName);           

            string pref1_value = groupUserDefaults.StringForKey("user_preference1");

            string[] notificationBodySplitAtDelimiterArray = notificationBody.Split(',');
            userPrefRegion = notificationBodySplitAtDelimiterArray[0];

            bool isCustomAlertSet = groupUserDefaults.BoolForKey("isCustomAlert");
            bool isCustomPhotoSet = groupUserDefaults.BoolForKey("isCustomPhotoSet");

            string alarmPath = isCustomAlertSet == true ? "customalert.wav" : "default_alert.m4a";

            if (isCustomPhotoSet)
            {
                 // this is the App Group url of the custom photo saved in PCL
                 imgPath = groupUserDefaults.StringForKey("imageAbsoluteString");             
            }
            else
            {
                imgPath = null;
            }

            if (imgPath != null )
            {                
                imgUrl = NSUrl.FromString(imgPath);
            }
            else
            {
                imgUrl = null;
            }

            if (!string.IsNullOrEmpty(pref1_value))
            {
                if (BestAttemptContent.Body.Contains(pref1_value))
                {

                   if (imgUrl != null)
                   {

                        // download the image from the AppGroup Container
                        var task = NSUrlSession.SharedSession.CreateDownloadTask(imgUrl, (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 + "customphoto.jpg";
                            var cacheFile = cachesFolder + fileName;
                            var attachmentUrl = NSUrl.CreateFileUrl(cacheFile, false, null);

                            NSError err = null;
                            NSFileManager.DefaultManager.Copy(tempFile, attachmentUrl, out err);

                            if (err != null)
                            {
                                ContentHandler(BestAttemptContent);
                                return;
                            }

                            UNNotificationAttachmentOptions options = null;
                            var attachment = UNNotificationAttachment.FromIdentifier("image", attachmentUrl, options, out err);

                            if (attachment != null)
                            {
                                BestAttemptContent.Attachments = new UNNotificationAttachment[] { attachment };
                            }    
                        });
                        task.Resume();
                   }                                        
                    BestAttemptContent.Title = "My Custom Title";
                    BestAttemptContent.Subtitle = "My Custom Subtitle";
                    BestAttemptContent.Body = "Notification Body";
                    BestAttemptContent.Sound = UNNotificationSound.GetSound(alarmPath);        
                }                 
            }
            else
            {
               pref1_value = "error getting extracting user pref";
            }        

            // finally display customized notification                 
            ContentHandler(BestAttemptContent);
        }

1 Ответ

0 голосов
/ 29 января 2019

/ private / var / mobile / Containers / Shared / AppGroup / 12F209B9-05E9-470C-9C9F-AA959D940302 / Pictures / customphoto.jpg

из общего кода при получении изображенияиз AppGroup. Вы можете проверить путь к файлу, если работа в этом проекте.

imgPath = groupUserDefaults.StringForKey("imageAbsoluteString"); 

Если не получить файл по этому пути.Вы можете получить Url из AppGroup напрямую. Вот пример:

var FileManager = new NSFileManager();
var appGroupContainer = FileManager.GetContainerUrl("group.com.company.appName");
NSUrl fileURL = appGroupContainer.Append("customphoto.jpg", false);

А если fileURL нельзя использовать напрямую, также можно преобразовать в NSData и сохранить в локальномфайловая система.Это также может быть попыткой.

Ниже приведен пример, извлекаемый из локальной файловой системы:

public static void Sendlocalnotification()
{       
    var localURL = "...";
    NSUrl url = NSUrl.FromString(localURL) ;

    var attachmentID = "image";
    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");
         }
     });

}
...