今日 iOS 小部件 来自锁定屏幕和通知中心的通用链接



我们有一个今天的小部件,可以深度链接到应用程序。当用户从主屏幕访问小部件时,深层链接工作得很好。但是,当用户在设备锁定时访问小组件时,或者当用户从屏幕顶部向下滑动时,链接会在 Safari 中打开。

我想知道是否有其他人遇到过这个问题,如果是,他们是如何解决的。

这是我们遇到的解决方案(Swift 4.1(。我们需要支持自定义 URL 方案,以告诉 iOS 我们可以从 today 小部件打开链接。这使用不同的 UIApplication 委托函数。在实现func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool的同时,我们还需要实现func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool

首先,在Info.plist,我们在CFBUndleURLTypes下有我们支持的方案。

<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>todayWidgetScheme</string>
</array>
</dict>
</array>

然后,同样在Info.plist,我们还在LSApplicationQueriesSchemes下列出了该计划。

<key>LSApplicationQueriesSchemes</key>
<array>
<string>todayWidgetScheme</string>
</array>

接下来,从 today 小部件打开链接时,将 url 方案设置为 iOS 识别的 todayWidgetScheme。

func openAppFromTodayWidget() {
if let url = URL(string: "https://url.com") {
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)
components?.scheme = "todayWidgetScheme"
if let todayWidgetUrl = components?.url {
extensionContext?.open(todayWidgetUrl)
}
}
}

最后,在AppDelegate.swift中,当 iOS 要求应用程序处理通用链接时,设置原始 url 方案

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if url.scheme == "todayWidgetScheme" {
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)
components?.scheme = "https"
if let todayWidgetUrl = components?.url {
// do your thing
return true
}
}
return false
}

最新更新