Загрузка изображения для показа в локальном уведомлении не работает - PullRequest
0 голосов
/ 26 октября 2019

Я разрабатываю платформу, которая имеет функции для получения сообщений от FCM и преобразования их в локальные уведомления. В одном из ключей, которые я получаю, есть URL-адрес изображения. Таким образом, проведя некоторые исследования в документации Apple, выяснилось, что изображение должно храниться на устройстве (я использую симулятор), а затем его можно использовать, поэтому я реализую метод загрузки случайного изображения (.png). Этот метод работает нормально, я тестирую его, и изображение находится в указанном месте, проблема в том, что когда я печатаю словарь userInfo из указателя NSError * при вызове метода attachmentWithIdentifier:identifier URL: options: error:, я получаю этот

{NSLocalizedDescription = "Invalid attachment file URL";}

Iприложите мой код:

UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
if (settings.alertSetting == UNNotificationSettingEnabled)
{

    NSDictionary * remoteMessageData = [remoteMessage appData];

    NSString * imageHttpUrl = [remoteMessageData objectForKey:@"im"];

    NSURL * imageURL = [self getStorageFilePath:imageHttpUrl];

    [self downloadImageFromURL:imageHttpUrl withFullPath:imageURL.absoluteString withCompletitionHandler:^(NSHTTPURLResponse *httpResponse) {

        UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc] init];

            content.title = [remoteMessageData objectForKey:@"ti"];
            content.body = [remoteMessageData objectForKey:@"bd"];

        if(httpResponse != nil)
        {
            if (httpResponse.statusCode == 200)
            {
                NSString * identifier = @"ImageIdentifier";
                NSArray<UNNotificationAttachment*> * attachments = [NSArray arrayWithObjects:[self getAttachments:imageURL withIdentifier:identifier], nil] ;
                content.attachments = attachments;
            }

        }

        content.userInfo = remoteMessageData;

        UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

        //Create and register a request notification
        NSString * uuidString = [[NSUUID UUID] UUIDString];

        UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:uuidString content:content trigger:trigger];


        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            //Handle error
            if(error != nil)
            {
                NSLog(@"Dictionary: %@",[error userInfo]);
            }
        }];



- (NSURL *) getStorageFilePath : (NSString *)imageStringURL{

if(imageStringURL == nil)
{
    return nil;
}

NSURL * imageURL = [NSURL URLWithString:imageStringURL];

NSString * fileName = [imageURL lastPathComponent];

NSLog(@"fileName %@",fileName);

NSArray * systemPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSLog(@"systemPaths %@",systemPaths);

NSString * tempDirectoryStringPath = [[[NSURL URLWithString:[systemPaths objectAtIndex:0]] absoluteString] stringByAppendingString:@"/"];

NSString * fullPath = [tempDirectoryStringPath stringByAppendingString:fileName];

NSLog(@"Full PATH: %@",fullPath);

return [NSURL URLWithString:fullPath];}

-(void) downloadImageFromURL : (NSString *)httpURL withFullPath:(NSString * )fullPath withCompletitionHandler:(void (^) (NSHTTPURLResponse * httpResponse) )taskResult{

if(httpURL == nil || fullPath == nil )
{
    taskResult(nil);
    return;
}

NSString *strImgURLAsString = httpURL;

strImgURLAsString = [strImgURLAsString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSURL * imgURL = [NSURL URLWithString:strImgURLAsString];

NSLog(@"Full PATH inside downloading: %@",fullPath);

NSURLSessionDataTask * downloadPhotoTask = [[NSURLSession sharedSession] dataTaskWithURL:imgURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

    if (httpResponse.statusCode == 200)
    {
        [data writeToFile:fullPath atomically:YES];



        NSLog(@"Download run successfully");


    }else{
        NSLog(@"Download could not be completed");


    }

    taskResult(httpResponse);

} ];

[downloadPhotoTask resume];


  }

- (UNNotificationAttachment *) getAttachments: (NSURL *)attachmentURL withIdentifier : (NSString*)identifier
{

    NSError * error;

    UNNotificationAttachment * icon =  [UNNotificationAttachment attachmentWithIdentifier:identifier URL: attachmentURL options:nil error:&error];

    NSLog(@"Icon is : %@",[error userInfo]);

    UNNotificationAttachment* attachments = icon;

    return (attachments);
}

1 Ответ

0 голосов
/ 26 октября 2019

Я мог бы заставить это работать. Я использовал [NSURL URLWithString: fullPath] NSURL, но я должен был использовать [NSURL fileURLWithPath: fullPath], но в методе downloadImageFromURL продолжайте использовать строковый URL-адрес без формата fileURLWithPath: метод (который заставляет изображение не загружаться).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...