Search code examples
iosnativescriptangular2-nativescript

Update NativeScript plugin nativescript-local-notifications to support images


I'm trying to update the NativeScript plugin nativescript-local-notifications to display images in the notifications.

That's already working on Android here, but I'm having some issues when trying to implement the same thing for iOS.

I have done some changes to the method schedulePendingNotificationsNew in local-notifications.ios.ts:

private static async schedulePendingNotificationsNew(pending: ScheduleOptions[]): Promise<void> {

    ...

    content.userInfo = userInfoDict; // Not changed

    if (options.image) {            
        const image: ImageSource = await imageSource.fromUrl(options.image);
        const imageName: string = options.image.split('/').slice(-1)[0];
        const imageExtension: "png" | "jpeg" | "jpg" = <"png" | "jpeg" | "jpg">imageName.split('.')[1]
        const folderDest = fileSystemModule.knownFolders.temp();
        const pathDest = fileSystemModule.path.join(folderDest.path, imageName);

        console.log(`Image will be saved to = ${ pathDest }`);

        const saved = image.saveToFile(pathDest, imageExtension);

        console.log(`Image ${ saved ? '' : 'not' } saved. `);
        console.log(`Image does ${ fileSystemModule.File.exists(pathDest) ? '' : 'not' } exist. `);

        if (saved || fileSystemModule.File.exists(pathDest)) {
            console.log('Attaching image...');

            try {
                const attachment = UNNotificationAttachment
                .attachmentWithIdentifierURLOptionsError('attachment', NSURL.fileURLWithPath('file://' + pathDest), null);
                // .attachmentWithIdentifierURLOptionsError('attachment', NSURL.fileURLWithPath(pathDest), null);

                content.attachments = NSArray.arrayWithObject<UNNotificationAttachment>(attachement);
            } catch(err) {
                console.log('Attachment error ; ', err);
            }

            console.log('Image attached!');
        }
    }

    const repeats = options.interval !== undefined; // Not changed

    ...
}

You can see I have created the attachment in two different ways:

const attachment = UNNotificationAttachment
    .attachmentWithIdentifierURLOptionsError('attachment', 
        NSURL.fileURLWithPath('file://' + pathDest), null);

And:

const attachment = UNNotificationAttachment
    .attachmentWithIdentifierURLOptionsError('attachment',
        NSURL.fileURLWithPath(pathDest), null);

But none of them work, in both cases I get a text-only notification and these logs:

Image will be saved to = /var/mobile/Containers/Data/Application/.../Library/Caches/1974-lancia-stratos-hf-stradale-for-sale.jpg
Image not saved.
Image does not exist.

I'm testing it on an iPhone 7 and an iPhone 8 and the image I'm trying to save is this one: https://icdn-0.motor1.com/images/mgl/7WjgW/s3/1974-lancia-stratos-hf-stradale-for-sale.jpg


Solution

  • I fixed it by forcing the image to be saved as png:

    export class LocalNotificationsImpl extends LocalNotificationsCommon implements LocalNotificationsApi {
    
        ...
    
        private static guid() {
            // Not the best, but will it will do. See https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
    
            const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    
            return `${ s4() }${ s4() }-${ s4() }-${ s4() }-${ s4() }-${ s4() }${ s4() }${ s4() }`;
        }
    
        private static getImageName(imageURL: string = "", extension: "png" | "jpeg" | "jpg" = "png"): [string, string] {
            const name: string = imageURL.split(/[\/\.]/).slice(-2, -1)[0] || LocalNotificationsImpl.guid();
    
            return [name, `${ name }.${ extension }`];
        }
    
        ...
    
        private static async schedulePendingNotificationsNew(pending: ScheduleOptions[]): Promise<void> {
    
            ...
    
            const imageURL: string = options.image;
    
            if (imageURL) {
                const image: ImageSource = await imageSource.fromUrl(imageURL);
                const [imageName, imageNameWithExtension] = LocalNotificationsImpl.getImageName(imageURL, "png");
                const path: string = fileSystemModule.path.join(
                    fileSystemModule.knownFolders.temp().path,
                    LocalNotificationsImpl.getImageName(imageURL, "png"),
                );
    
                const saved = image.saveToFile(path, "png");
    
                if (saved || fileSystemModule.File.exists(path)) {                
                    try {
                        const attachment = UNNotificationAttachment
                            .attachmentWithIdentifierURLOptionsError('attachment', NSURL.fileURLWithPath(path), null);
    
                        content.attachments = NSArray.arrayWithObject<UNNotificationAttachment>(attachment);
                    } catch(err) {}
                }
            }
    
            ...
    
        }
    }
    

    If you are interested, these changes have been merged to my fork of the plugin and there's a PR open in the official one.