【发布时间】:2019-09-16 18:07:07
【问题描述】:
我的应用程序已成功打开并将参数(来自 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
}
ViewController.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 个小时来解决此问题,但仍在第二次打印。
【问题讨论】:
-
好吧,每当应用打开首先调用的 appdelegate 类时
-
ViewController 第一次没有取变量真的很奇怪...
标签: ios swift viewcontroller appdelegate url-scheme