如何在 Objective-C 中设置 Amazon Amplify iOS?

How can I set up Amazon Amplify iOS in Objective-C?

docs 仅显示 Swift 代码。尝试使用 Objective-C 时,我无法访问任何 Amplify 库。我是否缺少安装步骤?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

do {
    try Amplify.add(plugin: AWSCognitoAuthPlugin())
    try Amplify.add(plugin: AWSPinpointAnalyticsPlugin())
    try Amplify.configure()
    print("Amplify configured with Auth and Analytics plugins")
} catch {
    print("Failed to initialize Amplify with \(error)")
}

return true

}

如何在 Objective-C 中执行等效操作?

Am I missing an installation step?

你没有遗漏任何东西。遗憾的是,iOS 的 Amplify 没有 Objective-C 支持。 Amplify 是在 Swift 中构建的,使用了它的全部功能,除非社区有强烈需求,否则目前不考虑 Objective-C 支持。


出于好奇:您要在 Objective-C 中启动新应用吗?如果是这样,我很想知道为什么不使用 Swift 鉴于 Apple 最近对 Swift 的投资(合并、SwiftUI、Swift 语言更新等).

如果您尝试将 Amplify 集成到现有的 Objective-C 应用中,恐怕无法实现。

是的,老旧的 Objective C 应用程序仍然存在。而且它们必须得到维护。期望开发人员在 Swift 中重写它们只是为了他们可以使用 Amplify 确实是不合理的。我最近被要求将 Amplify 添加到 Swift 存在之前 2015 年初构建的应用程序中。 (天啊——真的有 5 年以上的应用程序吗?!)

幸运的是,如果您能硬着头皮为您的 Objective C 项目添加 Swift 支持,那么制作 Swift 包装器 class 并不难您使用的 Objective C。这是我免费创建的一个。如果 Amazon 的高薪人士能够友好地帮助我们提供这样的示例,那就太好了。

import Amplify
import AmplifyPlugins

@objc
class AmplifyWrapper: NSObject {
    override init() {
        super.init()
    }
    @objc
    public func initialize() {
        do {
            try Amplify.add(plugin: AWSCognitoAuthPlugin())
            try Amplify.add(plugin: AWSPinpointAnalyticsPlugin())
            try Amplify.configure()
            print("Amplify configured with Auth and Analytics plugins")
        } catch {
            print("Failed to initialize Amplify with \(error)")
        }
    }
    @objc
    public func recordEvent(name: String, category: String, accountId: String) {
        let properties: AnalyticsProperties = [ "category": category, "accountId": accountId]
        let event = BasicAnalyticsEvent(name: name, properties: properties)
        Amplify.Analytics.record(event: event)
    }
}

像这样使用表格 Objective C:

#import "PutYourAppNameHere-Swift.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[[AmplifyWrapper alloc] init] initialize];
    ...
}

之后你可以这样做:

  [[[AmplifyWrapper alloc] init] recordEventWithName:@"App Opened" category:@"Counts" accountId:""];