我有一个带有链接的小工具.我要在SceneDelegate中实现小部件URL.问题是,当我点击小工具时,我会得到一个链接,它起作用了.但是,当我在SceneDelegate中调用View控制器函数时,它什么也不做.嗯,它可以打印一些东西,但它不会改变任何东西.SceneDelegate:

   // App launched
   func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = ViewController()
        self.window = window
        window.makeKeyAndVisible()
        getURL(urlContext: connectionOptions.urlContexts)
    }
    
    // App opened from background
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        getURL(urlContext: URLContexts) 
    }
    
    // Get URL
    private func getURL(urlContext: Set<UIOpenURLContext>) {
        guard let urlContexts = urlContext.first(where: { $0.url.scheme == "app-deeplink" }) else { return }
        print(urlContexts.url)
        print("success")
        let viewController = ViewController()
        viewController.cameFromWidget()
    }

更改标签文本的视图控制器中的函数:

func cameFromWidget() {
        label.text = "Hello"
        print(label.text)
    }

小窗口扩展名:

var body: some View {
        Text(entry.date, style: .time)
            .widgetURL(URL(string: "app-deeplink://app"))
    }

因此,当我从SceneDelegate开始调用时,视图控制器函数只打印文本,但不会更改它. 我的小部件链接只在WidgetExtension和SceneDelegate中,我没有将它添加到infoPlist中.

我的问题是:为什么它起作用了,却毫无作用?也许我应该把它加到某个文件里? 非常感谢!

推荐答案

我发现了.要在您的视图控制器中进行一些更改,您需要使用rootViewController进行更改:

private func getURL(urlContext: Set<UIOpenURLContext>) {
        guard let urlContexts = urlContext.first(where: { $0.url.scheme == "app-deeplink" }) else { return }
        print(urlContexts.url)
        print("success")
        let rootViewController = window?.rootViewController as? ViewController
        rootViewController?.cameFromWidget()
    }

Ios相关问答推荐

如何从Windows PC在iPhone上安装Flutter 应用程序

为什么iOS委派在KMM中不能正常工作?

@Query与SwiftData数据列表绑定

如何让替换视图淡入旧视图而不是交叉淡入淡出?

帧过渡动画有条件地工作

SwiftUI 我自己的渲染函数的返回类型是什么?

在所有 tableview / collectionview 中禁用滚动指示器

.onChange(of: ) 一次用于多个 @State 属性?

为什么我不能让 passthrough 科目为 combine 工作?

滑动以返回特定的 SwiftUI 视图

Swift如何表示单位转换的标准大气压

Xcode 6 App Store 提交失败并显示您的帐户已经拥有有效的 iOS 分发证书

Swift 错误:在其自己的初始值中使用的变量

通过 iOS 创建和导出动画 gif?

如何在 Xcode 4 中切换 .h 和 .m

在 iOS 7 上更改标签栏色调 colored颜色

iOS:如何从 URL 调试新启动应用程序

UISegmentedControl 以编程方式更改段数

Objective-C 将 NSDate 设置为当前 UTC

如何使用 AFNetworking 设置超时