在执行“perform”方法之前是否可以在应用程序意图构造函数中接收参数?

问题描述 投票:0回答:1

我试图在我的应用程序意向结构构造函数中接收一个参数,以使用此参数值执行操作,但执行方法在我自己的 init 执行之前执行。顺便说一下,WidgetConfigurationIntent协议强制我有一个空的init,即使我已经有了自己的构造函数,所以我需要有两个构造函数,第一个执行的是空构造函数,然后是perform方法。因此,我的“自定义”构造函数仅在这两个之后执行。这样,当我要在执行意图方法中使用 myParameter 的值时,我总是收到 nil。

有人知道如何解决吗?

我的意图是这样的:

struct ConfigurationAppIntent: WidgetConfigurationIntent {
    static var title: LocalizedStringResource = "Configuration"
    static var description = IntentDescription("This is an example widget.")
    
    var myParameter: MyCustomClass?
    
    init(myParameter: MyCustomClass?) {
        self.myParameter = myParameter
    }
    
    init() {}
    
    func perform() async throws -> some IntentResult {
        print("intent was executed")
        
        return .result()
    }
}
swift swiftui widgetkit appintents
1个回答
0
投票
It seems like you're encountering a common issue with intents and their initialization flow in Swift. When you conform to the WidgetConfigurationIntent protocol, you're required to have an empty initializer due to protocol requirements. This is why your custom initializer isn't being called first.

One way to solve this is by setting your parameter after the empty initialiser has been called. You can do this by creating a separate method to set your parameter value, which you can call after the intent object has been initialised. Here's how you can modify your code to achieve this:


struct ConfigurationAppIntent: WidgetConfigurationIntent {
    static var title: LocalizedStringResource = "Configuration"
    static var description = IntentDescription("This is an example widget.")
    
    var myParameter: MyCustomClass?
    
    init() {}
    
    mutating func setParameter(_ parameter: MyCustomClass) {
        self.myParameter = parameter
    }
    
    func perform() async throws -> some IntentResult {
        guard let myParameter = myParameter else {
            // Handle the case where myParameter is nil
            return .failure(/* Provide an appropriate error */)
        }
        
        print("Intent was executed with myParameter: \(myParameter)")
        
        // Perform your action using myParameter
        
        return .success(/* Provide the result if any */)
    }
}

    Then, after initialising an instance of ConfigurationAppIntent, you can call setParameter() to set the value of myParameter.

var intent = ConfigurationAppIntent()
intent.setParameter(/* Provide your custom parameter here */)

This way, you ensure that myParameter is set before calling the perform() method.
© www.soinside.com 2019 - 2024. All rights reserved.