如何将 AppDelegate Swift 代码放入 Objective-C AppDelegate 文件并使其工作?
Posted
技术标签:
【中文标题】如何将 AppDelegate Swift 代码放入 Objective-C AppDelegate 文件并使其工作?【英文标题】:How do I put AppDelegate Swift code into Objective-C AppDelegate file and make it work? 【发布时间】:2019-03-28 16:56:09 【问题描述】:我正在尝试使用名为 AWSAppSync 的适用于 ios 的 Amazon Web Serivces 开发工具包。我找到了good instructions for Swift。 我会尽量让这个问题更普遍地适用于所有 Obj-c/Swift 桥接问题:
AppDelegate.Swift 文件有一个代码 sn-p。但是,我的 AppDelegate 在 Objective-C 中。我已将它放入 Swift 文件中的一个函数(称为 awsConfig)中,在 Bridging-Header.h 中引用该文件,并从我的 AppDelegate.m 调用 Swift 文件中的函数:
// AppDelegate.m
#import "<ProductModuleName>-Swift.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
appsyncer *syncClass = [appsyncer new];
[syncClass awsConfig];
return YES;
这是 Swift 文件中的 sn-p。
// SwiftAppDelegateExtension.Swift
var appSyncClient: AWSAppSyncClient?
do
// You can choose the directory in which AppSync stores its persistent cache databases
let cacheConfiguration = try AWSAppSyncCacheConfiguration()
// AppSync configuration & client initialization
let appSyncServiceConfig = try AWSAppSyncServiceConfig()
let appSyncConfig = try AWSAppSyncClientConfiguration(appSyncServiceConfig: appSyncServiceConfig,
cacheConfiguration: cacheConfiguration)
appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
catch
print("Error initializing appsync client. \(error)")
当我想在另一个 Swift 文件中使用它时,像这样:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appSyncClient = appDelegate.appSyncClient
我得到错误:
(!)“AppDelegate”类型的值没有成员“appSyncClient”
为什么这不起作用?如果我的解决方法太难看,还有什么更好的方法来解决这个问题?
【问题讨论】:
为什么不直接把 Swift 代码翻译成 Objective C 呢? 【参考方案1】:这可能是因为您当前正在使用的版本,因为此问题可能与您正在使用的版本的问题有关。所以首先尝试使用不同的版本,因为这发生在我身上一次,我只是使用旧版本,因为编译器有轻微的变化,所以如果你可以尝试不同的版本,然后让我知道并确保报告您尝试过的版本失败了。
【讨论】:
我想你的意思是 Swift 版本?如果是这样,我正在使用 Swift 4.2 。需要先更新我的操作系统和 xcode 才能升级到 swift 5。稍后会回复您 嗨,你更新了 swift 了吗?如果你有它现在可以工作吗?【参考方案2】:我发现答案是一个小错误:原来我把 appDelegate.h 而不是 appDelegate.m 放在了我的桥接头文件中。更改后它可以工作。可能将 Swift 代码翻译成目标 C 会是一个更好的选择,但如果你不像我一样熟练掌握这两种语言,这会更容易。
【讨论】:
以上是关于如何将 AppDelegate Swift 代码放入 Objective-C AppDelegate 文件并使其工作?的主要内容,如果未能解决你的问题,请参考以下文章
我如何从目标 c 代码中获取 Swift AppDelegate 的参考
AppDelegate 中的 Swift UITabbar 阴影
如何在 Swift 中 3 秒后从 AppDelegate 中删除FromSuperview