如何在Objective-C的AppDelegate中调用Swift编写的AppLinkModule类方法或直接设置其静态变量
Hey there! Since you're new to Objective-C, let's break down exactly how to interact with your Swift-written AppLinkModule from AppDelegate.m—whether you want to call the setLink method or directly set the static appLink variable.
Step 1: Import the Swift Bridge Header
First, you need to make sure your Objective-C code can see your Swift classes. At the top of your AppDelegate.m file, add the auto-generated Swift bridge header (replace <YourProjectName> with your actual Xcode project name):
#import "<YourProjectName>-Swift.h"
This header is automatically created when you mix Swift and Objective-C in a project, and it lets Objective-C access all your @objc-annotated Swift code.
Option 1: Directly Set the Static appLink Variable
Your appLink is declared as an @objc static property in Swift, which means Objective-C exposes it as a class-level property with auto-generated getter and setter methods. You can set it directly like this:
// In AppDelegate.m (e.g., inside application:openURL:options:) [AppLinkModule setAppLink:@"https://your-desired-link.com"]; // If you need to read the value later, use: NSString *currentLink = [AppLinkModule appLink];
Option 2: Call the setLink Instance Method
Since setLink is an instance method of AppLinkModule, you'll need to create an instance of the class first, then call the method:
// In AppDelegate.m AppLinkModule *moduleInstance = [[AppLinkModule alloc] init]; [moduleInstance setLink:@"https://your-desired-link.com"];
Important Fix for Your Bridge File
Quick heads-up: Your current AppLinkModule.m bridge file has an error for the getLink method. The Swift method uses promise blocks, so you need to match the exact signature in the Objective-C bridge to ensure React Native can resolve the promise correctly:
// Replace your existing RCT_EXTERN_METHOD(getLink) with: RCT_EXTERN_METHOD(getLink:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
Example Use Case in AppDelegate
Here's how this might look if you're handling deep links in the application:openURL:options: method:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { // Extract the full deep link URL NSString *deepLink = url.absoluteString; // Option 1: Set the static variable directly [AppLinkModule setAppLink:deepLink]; // OR Option 2: Use the instance method // AppLinkModule *module = [[AppLinkModule alloc] init]; // [module setLink:deepLink]; return YES; }
内容的提问来源于stack exchange,提问作者SHA

