Ios 从首次未处理的方案加载url-appdelegate vs viewcontroller

Ios 从首次未处理的方案加载url-appdelegate vs viewcontroller,ios,swift,viewcontroller,appdelegate,url-scheme,Ios,Swift,Viewcontroller,Appdelegate,Url Scheme,我的应用程序正在成功打开并将参数(从URL方案,即myApp://sometextToPrint)设置为AppDelegate类中的一个变量,但每当我想处理这些参数时,从该URL打开应用程序时,它都会失败。我有一个前台应用程序检查器,它调用函数来打印给定的参数,但不知何故,它看起来好像AppDelegate比视图加载得晚,为什么视图在第一次加载时无法打印参数 我的代码如下所示: AppDelegate.m func application(_ app: UIApplication, open u

我的应用程序正在成功打开并将参数(从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个小时来修复此问题,但仍在继续第二次打印。

func application(_ app: UIApplication, open url: URL, 
    options: [UIApplication.OpenURLOptionsKey : Any] = [:]) 
    -> Bool {
进入

在该方法中,检查
启动选项
。如果它包含
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.
func applicationWillEnterForeground(_ application: UIApplication) {
    // Do your stuffs here 
}
尝试实现appDelegate的

application(_ app: UIApplication, open url: URL, options: 
[UIApplication.OpenURLOptionsKey : Any] = [:]) - method.
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 

}

每当应用程序打开名为first的appdelegate类时,ViewController第一次没有获取变量,这真的很奇怪。。。