ios - 下载用于在本地通知上显示的图像不起作用

标签 ios objective-c cocoa-touch unusernotificationcenter

我正在开发一个框架,该框架具有从 FCM 接收消息并将其转换为本地通知的功能,在我收到的键之一中有一个图像的 URL。所以在Apple文档中做了一些研究发现图像应该存储在设备中(我使用的是模拟器)然后就可以使用它,所以,我实现了一种下载随机图像(.png)的方法。这个方法工作正常,我测试它并且图像位于指定位置,问题是当我在调用 attachmentWithIdentifier:identifier URL: options: error: 方法时从 NSError* 指针打印 userInfo Dictionary 时我明白了

{NSLocalizedDescription = "Invalid attachment file URL";}

我附上我的代码:

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);
}

最佳答案

我可以让它发挥作用。我正在使用 [NSURL URLWithString:fullPath] NSURL 但我应该使用 [NSURL fileURLWithPath:fullPath] 但在方法 downloadImageFromURL 中继续使用不带 fileURLWithPath: 格式的字符串 URL:方法(这会导致图像无法下载)。

关于ios - 下载用于在本地通知上显示的图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565949/

相关文章:

ios - 使用 PerformSegueWithIdentifier 展开 Segue - 不起作用 - Swift 2.1

javascript - iOS 12 中的 PWA 在重新打开应用程序时不再重新执行 Javascript

iphone - UITextView 格线背景但错误的行高

iphone - 使用按钮而不是 ui 导航 Controller 在 View 之间切换

ios - 仅在首次打开应用程序时显示教程 View

ios - 当前 UIActivityViewController- LaunchServices :invalidationHandler called

ios - 如何在不在屏幕上闪烁顶部和底部之间的任何呈现的 VC 的情况下关闭带有动画的模态视图 Controller 堆栈?

iphone - UITabBarController - 模拟双击 UITabBarItem

objective-c - 从单独的窗口更新绘图的正确方法是什么?

ios - 打开 map 应用程序 iOS 6 后以编程方式返回 iOS 应用程序