OneSignal / OneSignal-iOS-SDK

OneSignal is a free push notification service for mobile apps. This plugin makes it easy to integrate your native iOS app with OneSignal. https://onesignal.com
Other
487 stars 263 forks source link

[question]: OneSignal Notification image doesnt appear #1414

Open wesamodeh opened 2 months ago

wesamodeh commented 2 months ago

How can we help?

i implemented the OneSignalNotificationServiceExtenstion but when i send a notification includes image didnt appear , can u help ?

NotificationService code :

import UserNotifications
import OneSignalExtension

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var receivedRequest: UNNotificationRequest!
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.receivedRequest = request
        self.contentHandler = contentHandler
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        if let bestAttemptContent = bestAttemptContent {
            OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)

            // Handle attachment
            if let attachments = bestAttemptContent.userInfo["attachments"] as? [[String: Any]] {
                if let attachmentURLString = attachments.first?["url"] as? String, let attachmentURL = URL(string: attachmentURLString) {
                    do {
                        let attachment = try UNNotificationAttachment(identifier: "image", url: attachmentURL, options: nil)
                        bestAttemptContent.attachments = [attachment]
                    } catch {
                        print("Error creating attachment: \(error.localizedDescription)")
                    }
                }
            }
        }
    }

    // Function to download attachment data
    private func downloadAttachment(from urlString: String) -> URL? {
        if let url = URL(string: urlString) {
            do {
                let data = try Data(contentsOf: url)
                let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(url.lastPathComponent)
                try data.write(to: tempURL)
                return tempURL
            } catch {
                print("Error downloading attachment: \(error.localizedDescription)")
                return nil
            }
        }
        return nil
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
}

AppDelegate code :

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <Firebase.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 [FIRApp configure];
 self.moduleName = @"newVersion";

[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
   if (!granted && error == nil) {
       dispatch_async(dispatch_get_main_queue(), ^{
           [[UIApplication sharedApplication] registerForRemoteNotifications];
       });
   }
}];

 self.initialProps = @{};

 return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
 return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
 return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

PodFile code

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignalXCFramework', '3.12.9'
end

Code of Conduct

nan-li commented 1 month ago

Hi @wesamodeh, I don't see anything obvious that could be a problem.

I would recommend first checking that the OneSignalNotificationServiceExtenstion is actually running by adding these two lines to your code:

if let bestAttemptContent = bestAttemptContent {
    /* DEBUGGING: Uncomment the 2 lines below to check this extension is executing
                  Note, this extension only runs when mutable-content is set
                  Setting an attachment or action buttons automatically adds this */
    print("Running NotificationServiceExtension")
    bestAttemptContent.body = "[Modified] " + bestAttemptContent.body

    OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
}

If the OneSignalNotificationServiceExtenstion runs, you will see your notifications have the word "[Modified] ".

If the OneSignalNotificationServiceExtenstion runs but you are not able to see the image, then something else is the issue, please let us know about the first step.