0

I am using Swift 4.1 and I am wondering how to pass the url data that is given here:

func application(_ app: UIApplication, open url: URL,
                    options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
}

into my subclass of UIViewController I called HotSpotRISViewController. Here is what I attempted:

func application(_ app: UIApplication, open url: URL,
                    options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let vc = HotSpotRISViewController()
    vc.setURL(theURL: url)
    let navigationController = UINavigationController(rootViewController: vc)
    self.window!.rootViewController = navigationController

}

My HotSpotRISViewController contains this function:

func setURL(theURL: URL) {
    self.url = theURL
    print(self.url ?? "nil")
}

Inside my HotSpotRISViewController I have a property of type URL ready to be set. The above code correctly passes the info, because my print statement prints out the URL, but I get a black screen instead of my app. What am I missing? And then on the other hand, the following makes the app start up correctly but I have no idea how to pass the url data using this method:

func application(_ app: UIApplication, open url: URL,
                    options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewController = mainStoryboard.instantiateInitialViewController()
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
}

I'm wondering how I can get both my app started up correctly without a black screen and pass the url data. Thank you.

4

1 回答 1

3

您可以在 appDelegate 文件中添加一个全局变量,并使用您的 setURL 函数获取它:

在你的 AppDelegate.swift

    var myurl: URL!
    ....

    func application(_ app: UIApplication, open url: URL,
                options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        self.myurl = url
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = mainStoryboard.instantiateInitialViewController()
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    }
    ...

在你的 HotSpotRISViewController.swift

func setURL(theURL: URL) {
    DispatchQueue.main.async {
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            self.url = appDelegate.myurl
        }
    }
于 2018-05-08T09:00:33.890 回答