I have been trying to execute some code to open another app on the phone when a button is pressed on a widget for an app I’m building, but it seems as though it’s not possible to execute it from the widget extension.
When I try to build the code below (both files target the widget extension), I see a build error “‘shared’ is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead.“
When I change the target of the AppIntent to the main application it builds without any issues. With this in mind, and after some searching, some other approaches I’ve tried and failed to implement are:
- target both the widget extension and app, but this still breaks the build.
- move the AppIntent to the application and expose the function call somehow, though I’m not 100% sure what the correct way to do this is.
I’m not a new developer but I’m pretty new to Swift, so apologies if I’m missing something very obvious, but I haven’t been able to find a good solution for this use case. Ultimately what I’m trying to understand is
- Is it possible/recommended to expose an AppIntent or function from the app to the widget extension without directly targeting both? For example, could I route button clicks on the widget through the app using deep links and conditionally direct to other apps on the phone within the application layer?
- Is there a better approach here that I’m missing?
Thanks in advance for your help.
// The AppIntent that responds to the button press
struct LaunchApp : AppIntent {
static var title: LocalizedStringResource = "Launch an App"
func perform() async throws -> some IntentResult & ProvidesDialog {
let phoneUrl = URL(string: "mobilephone://")!
if await UIApplication.shared.canOpenURL(phoneUrl){
await UIApplication.shared.open(phoneUrl)
}
return .result(dialog: "Opening app..")
}
}
// The widget that contains the button
struct launchwidgetEntryView : View {
var entry: Provider.Entry
var body: some View {
VStack{
Button(intent: LaunchApp()){
Text("Books")
.font(.system(size: 30, weight: .bold, design: .monospaced))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
}
}
}
}
OohDidYeAye is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.