我的应用程序成功打开并设置参数(从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并点击以下网址:myApp:// printthistext,则不会打印文本。当我单击主页按钮并再次单击该应用程序时,它会打印出来。
附:我是swift的新手,并且不知道到底是先加载/处理了哪个类(AppDelegate或ViewContoller)。我已经尝试了将近5个小时来解决这个问题,仍然是第二次打印。
复制您的代码
func application(_ app: UIApplication, open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:])
-> Bool {
成
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
}
@SalihanPamuk我认为这是由于appWillEnterForeground()
方法。 UIApplication.willEnterForegroundNotification
- 这是发布应用程序的第一个通知。
由于您已经注册了一个观察者来收听此通知,因此appWillEnterForeground()
方法将在appDelegate之前调用
application(_ app: UIApplication, open url: URL, options:
[UIApplication.OpenURLOptionsKey : Any] = [:]) - method.
尝试实现appDelegate的
func applicationWillEnterForeground(_ application: UIApplication) {
// Do your stuffs here
}
或者,如果您想在使用任何URL设置打开应用程序后显示任何特定的ViewController,则显示该ViewController内部的代码
func application(_ app: UIApplication, open url: URL, options:
[UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// implemet your code here
}