使用异步函数初始化应用程序 |用户界面 [英] Initialize app with an Async function | SwiftUI
问题描述
我需要我的应用程序在开始时配置后端,这是这样做的功能:
I need my app to configure the backend at start, here's the function to do so:
// 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 中:
I tried placing it in the @main init like so:
init() async {
await networkController.configureAmplify()
}
但我收到以下错误:
Type 'MyApplicationNameApp' does not conform to protocol 'App'
我尝试在初始化之后应用建议:
I try to apply the suggestions after that which is to initialize it:
init() {
}
但这似乎很奇怪,所以现在我有 2 个 init.d .这里发生了什么以及在应用程序开始时初始化多个异步函数的正确方法是什么,例如:
but it seems odd, so now I have 2 init. What is going on here and what is the correct way to initialize multiple async functions at the start of the app, example:
- 上面的代码(配置放大)
- 检查用户是否登录
- 设置会话
等
注意:init() async
在上面的例子中永远不会被调用,这是这个问题中的另一个问题,那么在应用程序启动时初始化异步函数的正确方法是什么.
Note: The init() async
never gets called in the example above which is another problem within this question, so what is the correct way to initialize async function when the app starts.
推荐答案
使用 ViewModifier
.task{
await networkController.configureAmplify()
}
您可以将 Task
添加到 init
,但您可能会遇到问题,因为 SwiftUI 可以根据需要重新创建 View
You can add a Task
to the init
but you might have issues because SwiftUI can re-create the View
as it deems necessary
init(){
Task(priority: .medium){
await networkController.configureAmplify()
}
}
或者你可以使用一个 ObservableObject
,它是一个 @StateObject
Or you can use an ObservableObject
that is an @StateObject
使用 @StateObject
SwiftUI 只会为每个声明对象的结构实例创建一个新的对象实例.
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)")
}
}
}
这篇关于使用异步函数初始化应用程序 |用户界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!