gpt4 book ai didi

swiftui - 使用异步函数初始化应用 | swift 用户界面

转载 作者:行者123 更新时间:2023-12-05 08:47:00 26 4
gpt4 key购买 nike

我需要我的应用程序在启动时配置后端,这是执行此操作的函数:

// Initializes Amplify
final func configureAmplify() async {
do {
// Amplify.Logging.logLevel = .info
let dataStore = AWSDataStorePlugin(modelRegistration: AmplifyModels())
let syncWithCloud = AWSAPIPlugin()
let userAuth = AWSCognitoAuthPlugin()

try Amplify.add(plugin: userAuth)
try Amplify.add(plugin: dataStore)
try Amplify.add(plugin: syncWithCloud)
try Amplify.configure()
print("Amplify initialized")
} catch {
print("Failed to initialize Amplify with \(error)")
}
}

我试过像这样将它放在@main init 中:

init() async {
await networkController.configureAmplify()
}

但我收到以下错误:

Type 'MyApplicationNameApp' does not conform to protocol 'App'

我尝试在初始化它之后应用建议:

init() {

}

但这看起来很奇怪,所以现在我有 2 个 init.这里发生了什么以及在应用程序启动时初始化多个异步函数的正确方法是什么,示例:

  1. 上面的代码(配置放大)
  2. 检查用户是否登录
  3. 设置 session

等等

注意:init() async 在上面的示例中从未被调用,这是这个问题中的另一个问题,那么在应用程序启动时初始化异步函数的正确方法是什么。

最佳答案

使用ViewModifier

.task{
await networkController.configureAmplify()
}

您可以将 Task 添加到 init,但您可能会遇到问题,因为 SwiftUI 可以在它认为必要时重新创建 View

init(){
Task(priority: .medium){
await networkController.configureAmplify()
}
}

或者你可以使用一个ObservableObject,它是一个@StateObject

With an @StateObject SwiftUI creates a new instance of the object only once for each instance of the structure that declares the object.

https://developer.apple.com/documentation/swiftui/stateobject

@main
struct YourApp: App {
@StateObject var networkController: NetworkController = NetworkController()

var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class NetworkController: ObservableObject{

init() {
Task(priority: .medium){
await configureAmplify()
}
}
// Initializes Amplify
final func configureAmplify() async {
do {
// Amplify.Logging.logLevel = .info
let dataStore = AWSDataStorePlugin(modelRegistration: AmplifyModels())
let syncWithCloud = AWSAPIPlugin()
let userAuth = AWSCognitoAuthPlugin()

try Amplify.add(plugin: userAuth)
try Amplify.add(plugin: dataStore)
try Amplify.add(plugin: syncWithCloud)
try Amplify.configure()
print("Amplify initialized")
} catch {
print("Failed to initialize Amplify with \(error)")
}
}
}

关于swiftui - 使用异步函数初始化应用 | swift 用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68668770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com