Как решить NSObject неопределенную ошибку в платформе Android с помощью nativescript-angular? - PullRequest
0 голосов
/ 25 сентября 2019

Hai iam разрабатывает приложения для Android и IOS с использованием собственного script-angular. У меня возникла проблема при доступе к собственным API-интерфейсам для Android и IOS.В моем приложении есть функция удаления доставленных уведомлений, запускаемых сервером fcm при выходе из приложения. Я добавил код для удаления доставленных уведомлений путем доступа к методам собственных делегатов android и ios соответственно.Я удалил доставленное уведомление на платформе ios, используя собственные методы делегата ios.но NSObject Произошла неопределенная ошибка при работе на платформе Android.Как решить эту проблему?

Мой класс делегата Ios

import { DeliveredNotificationApi, LocalNotificationsCommon } from "./delivered_notification"
import { android as androidApp, ios as iosApp } from "tns-core-modules/application";

export class CustomNotification extends LocalNotificationsCommon implements  DeliveredNotificationApi
{

    private delegate: UNUserNotificationCenterDelegateImpl1;


    constructor()
    {
        super();
        if(CustomNotification.isUNUserNotificationCenterAvailable())
        {
            this.delegate = UNUserNotificationCenterDelegateImpl1.initWithOwner(new WeakRef(this));
            UNUserNotificationCenter.currentNotificationCenter().delegate = this.delegate;
        }
    }
    removeDeliveredNotification(): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
              if (CustomNotification.isUNUserNotificationCenterAvailable()) {
                UNUserNotificationCenter.currentNotificationCenter().removeAllDeliveredNotifications();
              } 
            //   else {
            //     UIApplication.sharedApplication.cancelAllLocalNotifications();
            //   }
            //   UIApplication.sharedApplication.applicationIconBadgeNumber = 0;
              resolve();
            } catch (ex) {
              console.log("Error in LocalNotifications.cancelAll: " + ex);
              reject(ex);
            }
          });
          }

    static isUNUserNotificationCenterAvailable(): boolean {
        try {
          // available since iOS 10
          return !!UNUserNotificationCenter;
        } catch (ignore) {
          return false;
        }
      }

}
class UNUserNotificationCenterDelegateImpl1 extends NSObject implements UNUserNotificationCenterDelegate {
    public static ObjCProtocols = [];

    private _owner: WeakRef<CustomNotification>;
    private receivedInForeground = false;

    public static new(): UNUserNotificationCenterDelegateImpl1 {
      try {
        UNUserNotificationCenterDelegateImpl1.ObjCProtocols.push(UNUserNotificationCenterDelegate);
      } catch (ignore) {
      }
      return <UNUserNotificationCenterDelegateImpl1>super.new();
    }

    public static initWithOwner(owner: WeakRef<CustomNotification>): UNUserNotificationCenterDelegateImpl1 {
      const delegate = <UNUserNotificationCenterDelegateImpl1>UNUserNotificationCenterDelegateImpl1.new();
      delegate._owner = owner;
      return delegate;
    }

  }
  var instance;
  instance = new CustomNotification();
  export const CustomLocalNotification = instance;

Класс моего делегата Android:

import { LocalNotificationsCommon, DeliveredNotificationApi } from "./delivered_notification";
import * as app from "tns-core-modules/application";
import * as utils from "tns-core-modules/utils/utils";


declare const android, com, global: any;

const NotificationManagerCompatPackageName = useAndroidX() ? global.androidx.core.app : android.support.v4.app;

function useAndroidX () {
  return global.androidx && global.androidx.appcompat;
}
(() => {
    const registerLifecycleEvents = () => {
      com.deemsysinc.ordernextseller.LifecycleCallbacks.registerCallbacks(app.android.nativeApp);
    };

    // Hook on the application events
    if (app.android.nativeApp) {
      registerLifecycleEvents();
    } else {
      app.on(app.launchEvent, registerLifecycleEvents);
    }
  })();


export class CustomNotification extends LocalNotificationsCommon implements DeliveredNotificationApi
{

    removeDeliveredNotification(): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
              const context = utils.ad.getApplicationContext();

              const keys: Array<string> = com.deemsysinc.ordernextseller.Store.getKeys(utils.ad.getApplicationContext());

              for (let i = 0; i < keys.length; i++) {
                CustomNotification.cancelById(parseInt(keys[i]));
              }

              NotificationManagerCompatPackageName.NotificationManagerCompat.from(context).cancelAll();
              resolve();
            } catch (ex) {
              console.log("Error in LocalNotifications.cancelAll: " + ex);
              reject(ex);
            }
          });

    }
    private static cancelById(id: number): void {
        const context = utils.ad.getApplicationContext();
        const notificationIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationAlarmReceiver.class).setAction("" + id);
        const pendingIntent = android.app.PendingIntent.getBroadcast(context, 0, notificationIntent, 0);
        const alarmManager = context.getSystemService(android.content.Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        const notificationManager = context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(id);

        com.deemsysinc.ordernextselle.Store.remove(context, id);
      }


}
export const CustomLocalNotificationAndroid = new CustomNotification();

Доступ к ios делегату этого класса

import {CustomLocalNotification } from "~/app/Utils/local_notification_custom";

    Logout()
    {
        if(iosApp)
        {
            CustomLocalNotification.removeDeliveredNotification();
        }
        this.routerExtension.navigate(['/login']); 
    }
...