【发布时间】:2021-04-27 11:11:34
【问题描述】:
此代码来自 Swift 项目 App 委托。它用于帮助使用可发布的密钥配置 Stripe。
//Appdelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
//The code helps configure Stripe with a publishable key.
STPPaymentConfiguration.shared().publishableKey = Constants.publishableKey
...
}
将 Swift 行添加到 Objective C App Delegate 后构建应用时显示两个错误
//AppDelegate.h
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
STPPaymentConfiguration.shared().publishableKey = Constants.publishableKey
Property 'shared' not found on object of type 'STPPaymentConfiguration'
Use of undeclared identifier 'Constants'
这是在将@objc 添加到演示 Swift 函数 MockApiClient 之前编译时出现的类似错误。它应该添加到其他地方吗?我已尝试将@objc 添加到此处的答案中提到的枚举中,但无济于事。
//Constants.swift
//This is the file the original Swift app delegate accesses
import Foundation
enum Constants {
static let publishableKey = "pk_live_..."
static let baseURLString = "http://54.33.123.227:1234"
static let defaultCurrency = "usd"
static let defaultDescription = "Receipt" //change to describe actual app & charge
}
采取的步骤:
-
打开 Objective C 项目并创建一个桥接头
-
还在 Obj C 项目中时在 Swift 中创建了一个演示类,以确保它可以使用,在这种情况下,当视图加载时从 Objective C 文件中打印。具体派生自一个 NSObject。将覆盖添加到初始化程序并使用
@objc前缀。// MockApiClient.swift import Foundation class MockApiClient: NSObject { override init() { print("Initializer called in Mock API client") } @objc func executeRequest() { print("The execute request has been called in the Mock API Client") } } //ViewController.h //Prints the Swift request written in the MockApiClient the the view loads @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. MockApiClient *client = [MockApiClient new]; [client executeRequest]; } -
将
#import "ViewController.h"导入复制到自动生成的project-Bridging-Header.h文件中,以便将其中的Objective C 公开给swift -
将必要的 Swift 文件添加到 Objective C 项目,以便可以找到来自
Constants.swift的Constants.publishablekey数据
如何将此 Swift App 委托代码添加到 Objective C 项目的 App 委托中?
编辑:将@objc 添加到Constants.swift 中的enum 声明时出错
【问题讨论】:
-
如果 STPPaymentConfiguration 和 Constants 是 Swift 对象,那么要被 Objective-C 看到,它们需要是 Objective-C 可以 看到的类型(即用 @ 暴露的类987654337@),Objective-C文件需要导入自动生成的头文件(与“添加”头文件无关)。
标签: ios swift iphone xcode cocoa-touch