更新 NativeScript 插件 nativescript-local-notifications 以支持图像

Update NativeScript plugin nativescript-local-notifications to support images

我正在尝试更新 NativeScript 插件 nativescript-local-notifications 以在通知中显示图像。

这已经在 Android here 上起作用了,但是我在尝试为 iOS.

实施同样的事情时遇到了一些问题

我对local-notifications.ios.ts中的方法schedulePendingNotificationsNew做了一些修改:

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

    ...
}

您可以看到我用两种不同的方式创建了附件:

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

并且:

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

但其中 none 有效,在这两种情况下我都收到纯文本通知和这些日志:

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.

我正在 iPhone 7 和 iPhone 8 上测试它,我要保存的图像是这个:https://icdn-0.motor1.com/images/mgl/7WjgW/s3/1974-lancia-stratos-hf-stradale-for-sale.jpg

我通过强制将图像保存为 png:

来修复它
export class LocalNotificationsImpl extends LocalNotificationsCommon implements LocalNotificationsApi {

    ...

    private static guid() {
        // Not the best, but will it will do. See 

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

        ...

    }
}

如果您有兴趣,这些更改已合并到 my fork of the plugin and there's a PR open in the official one