我的应用程序已成功打开并将参数(从 URL 方案,即 myApp://sometextToPrint)设置为AppDelegate
类,但每当我想处理它们时,当从该 URL 打开应用程序时,它就会在第一次失败。我在前台检查器中有一个应用程序,它调用打印给定参数的函数,但不知怎的,它看起来像AppDelegate
加载时间晚于视图,为什么视图在首次加载时无法打印参数。
我的代码如下所示:
AppDelegate.m
func application(_ app: UIApplication, open url: URL, options:
[UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let geturl = url.host?.removingPercentEncoding;
UserDefaults.standard.set(geturl, forKey: "DeepLinkUrl")
return true
}
视图控制器.m
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground),name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func appWillEnterForeground() {
print("app on foreground")
let user = UserDefaults.standard
if user.url(forKey: "DeepLinkUrl") != nil {
let str = user.value(forKey: "DeepLinkUrl") as! String
print(str) //this is printed on the second time when I click home button and open app again
}
}
例如,如果我转到 Safari 并点击以下 URL:myApp://printthistext,则不会打印文本。当我单击主页按钮并再次单击该应用程序时,它会打印。
附注我是 swift 的新手,还不知道首先加载/处理哪个类(AppDelegate 或 ViewContoller)。我已经尝试了近 5 个小时来解决这个问题,仍然继续第二次打印。
复制您的代码
func application(_ app: UIApplication, open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:])
-> Bool {
into
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?)
-> Bool {
在该方法中,检查launchOptions
。如果它包含url
键,获取该值 - 然后返回false
.
if let url = launchOptions[.url] as? URL {
let geturl = url.host?.removingPercentEncoding
UserDefaults.standard.set(geturl, forKey: "DeepLinkUrl")
return false
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)