从Widget(今日扩展)打开主机应用程序时未调用AppDelegate函数

时间:2018-04-21 15:05:54

标签: ios swift widget url-scheme today-extension

目标

从今天扩展(小部件)打开应用程序,并根据按钮点击执行不同的操作。

  • 目标:iOS 10

帖子&文章被判

已经完成

创建URLScheme

目标/ MyApp / Info / URLTypes

  • 网址类型标识符 = com.myCompany.MyAppName
  • URLType URLSchemes = MyAppName
  • 网址类型角色 =查看器

从Widget

打开主机应用程序

TodayViewController(Widget)

@IBAction func addButtonPressed(_ sender: UIButton) {
  let url = URL(string: "MyAppName://")!

  extensionContext?.open(url) { isSuccess in
    switch isSuccess {
    case true: print("Open URL Success") // It print when opening app
    case false: print("Open URL Failed")
    }
  }
}

按下时按钮效果很好。主机应用程序已启动。

委托func应用程序(_:open:options :)未调用

AppDelegate(主机应用程序)

// This delegate function is never called when the host application launches
func application(_ app: UIApplication, // breakpoint doesn't trigger
               open url: URL,
               options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { 

  print("FUNCTION CALLED ") // Never print

  return true
}

当主机应用程序从Widget中的按钮点击打开时,永远不会调用此委托函数。当从窗口小部件打开应用程序时,我的应用程序如何运行一些代码。 我尝试使用其他一些方法,但它们已被弃用。

我继续搜索,当小部件打开主机应用程序时,看起来没有AppDelegate函数可以被调用,因为当应用程序启动时不会调用所有其他方法,如applicationWillEnterForeground

我试过一台真正的设备,但它仍然没有用。

1 个答案:

答案 0 :(得分:2)

转到您的应用目标然后信息 - >网址类型 - >添加URL方案

在TodayViewController中

粘贴以下代码

self.extensionContext?.open(URL(string: "Your URL Scheme identifier")!, completionHandler: nil)