You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改OpenIntent代码实现iOS18控件Widget打开指定URL?

iOS18 Control Widget 用OpenIntent打开指定URL的解决方案

核心修改思路

iOS18的Control Widget扩展禁止调用UIApplication.shared.open(_:),需改用系统提供的OpenIntent来实现URL打开逻辑——通过在自定义AppIntent中创建OpenIntent实例并返回,由系统自动处理打开操作。

完整代码示例

import AppIntents

struct OpenCustomURLIntent: AppIntent {
    static let title: LocalizedStringResource = "打开指定链接"
    static let description = IntentDescription("快速打开预设的目标网址")
    
    // 若需让用户自定义URL,可添加以下参数(根据需求启用)
    // @Parameter(title: "目标网址") var urlString: String
    
    func perform() async throws -> some IntentResult & ReturnsValue<OpenIntent> {
        // 替换为你需要打开的目标URL
        guard let targetURL = URL(string: "https://example.com") else {
            throw AppIntentError.invalidURL
        }
        
        // 创建系统OpenIntent实例,传入目标URL
        let openIntent = OpenIntent(openURL: targetURL)
        // 返回结果并关联OpenIntent,系统将自动执行打开操作
        return .result(value: openIntent)
    }
    
    // 自定义错误类型,用于处理URL解析失败等场景
    enum AppIntentError: Error, LocalizedError {
        case invalidURL
        
        var errorDescription: String? {
            switch self {
            case .invalidURL: return "无法解析目标网址"
            }
        }
    }
}

关键说明

  1. 替换UIApplication调用:完全移除UIApplication.shared.open(_:),改用OpenIntent封装URL,由系统接管打开流程
  2. 返回值类型:perform方法需返回IntentResult & ReturnsValue<OpenIntent>,确保系统能识别并执行关联的OpenIntent
  3. 自定义URL支持:如果需要让用户在添加控件时输入自定义URL,可启用代码中的@Parameter参数,将用户输入的字符串转为URL后传入OpenIntent
  4. 权限与配置:
    • 打开HTTP/HTTPS链接无需额外配置;若使用自定义URL Scheme,需在主App的Info.plist中添加对应Scheme到LSApplicationQueriesSchemes数组
    • 确保WidgetExtension的Info.plist已配置IntentsSupported数组,包含你的自定义Intent类名

内容的提问来源于stack exchange,提问作者Gizmodo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:43:11