来自 appdelegate IOS 的 Cordova 调用插件代码

Cordova call plugin code from appdelegate IOS

我正在尝试为 Cordova 应用程序构建插件。在这个插件中,我有一些用于推送通知的本机代码。我已经在插件中添加了所需的文件,现在我正在尝试从应用程序的 AppDelegate.m 调用 header。但是导入有错误“找不到文件”。我在插件的 plugin.xml 中添加了 header 文件,如下所示: < header-file src="src/ios/xxxxx/xxxxx.h" /> 有什么想法吗?

当 Cordova 创建 iOS 平台项目时,

AppDelegate.m 是 auto-generated,因此不建议直接修改它,因为如果您使用 cordova plugin rm ios && cordova platform add ios 重建平台项目,任何更改都将丢失。

插件可以通过使用 AppDelegate class 的类别扩展来解决这个问题,它允许您在不影响 auto-generated 文件的情况下捆绑扩展插件仓库中 AppDelegate 的代码.

例如,您将创建 myplugin/src/ios/AppDelegate+MyPlugin.h:

#import "AppDelegate.h"

@interface AppDelegate (MyPlugin) <UIApplicationDelegate>
@end

然后在myplugin/src/ios/AppDelegate+MyPlugin.m中你可以实现你的app delegate,例如:

#import "AppDelegate+MyPlugin.h"

@implementation AppDelegate (MyPlugin)


// A UIApplication delegate
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"Remote notification received");
}

...

为了让您的 AppDelegate 类别与您的 Cordova 插件交互 class,您可以公开一个 public 方法,returns AppDelegate 类别可以调用它的单例实例;例如:

myplugin/src/ios/MyPlugin.h:

#import <Cordova/CDV.h>

@interface MyPlugin : CDVPlugin

// Public static method
+ (MyPlugin*) myPlugin;

// A public instance method
- (void)logMessage: (NSString*)msg;

@end

myplugin/src/ios/MyPlugin.m:

#import "MyPlugin.h"

@implementation MyPlugin

// Private static reference
static MyPlugin* myplugin;

// Public static method
+ (MyPlugin*) myplugin {
    return myplugin;
}


// implement CDVPlugin delegate
- (void)pluginInitialize {
    myplugin = self;
}


// A public instance method
- (void)logMessage: (NSString*)msg
{
    NSLog(@"MyPlugin: %@", msg);
}

@end

然后在myplugin/src/ios/AppDelegate+MyPlugin.m你可以使用你的插件方法:

#import "AppDelegate+MyPlugin.h"
#import "MyPlugin.h"

@implementation AppDelegate (MyPlugin)


// A UIApplication delegate
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [MyPlugin.myPlugin logMessage:@"Remote notification received"];
}

...

采用这种方法的插件示例是 cordova-plugin-firebasex