简体   繁体   中英

How do I put AppDelegate Swift code into Objective-C AppDelegate file and make it work?

I'm trying to work with an Amazon Web Serivces SDK for iOS called AWSAppSync. I found good instructions for Swift . I'll try to make the question more general to all Obj-c/Swift bridging problems:

There's a code snippet for the AppDelegate.Swift file. However, my AppDelegate is in Objective-C. I've put it into a function (called awsConfig) within a Swift file, referenced the file in the Bridging-Header.h and called the function in the Swift file from my AppDelegate.m:

// AppDelegate.m
#import "<ProductModuleName>-Swift.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    appsyncer *syncClass = [appsyncer new];
    [syncClass awsConfig];

    return YES;
}

And here's the snippet within the Swift file.

// 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)")
    }

When I want to use it in another Swift file, like this:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appSyncClient = appDelegate.appSyncClient

I get the error:

(!) Value of type 'AppDelegate' has no member 'appSyncClient'

Why doesn't this work? And what would be a better way to tackle this problem if my workaround is too ugly?

this might be because of the version you currently are working with since this issue can relate to the problem of the versions you are using. So try to use a different version first since this happened to me once and i just used a old version since there are slight changes to the compiler so if you can try different versions and then let me know and make sure to make a report of the versions you tried that failed.

I found the answer to be a slight error: Turns out I put appDelegate.h instead of appDelegate.m in my bridging-header file. After changing that it works. Probably translating the Swift code to objective C would've been a better option, but this is easier if you're not as skilled in both languages like I am.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM