如何通过Swift 4.2中的通知传递URL以在WebView中打开

时间:2018-12-15 02:15:26

标签: ios swift webview

到目前为止,在我的代表中,我已经能够从通知中成功获取URL,但我遇到的问题是如何将该URL传递给viewcontroller.swift以在webview中打开该URL。我从堆栈中尝试了几个示例,但它们似乎不适用于Swift 4.2。谁能帮我?抱歉,我是新来的。

AppDelegate.swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    let data = userInfo as! [String: AnyObject]

    let state = UIApplication.shared.applicationState

    if state == .background {
        // background
        print("==== Active Running ====")
        if let aps = data["aps"] {
            let url = aps["url"]
        }
    }
    else if state == .inactive {
        // inactive
        print("==== Inactive Running ====")
        if let aps = data["aps"] {
            let url = aps["url"]
        }
    }
    else if state == .active {
        // foreground
        print("==== Foreground Running ====")
        if let aps = data["aps"] {
            let url = aps["url"]
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您要从头开始初始化该视图控制器,则可以在您的Appdelegate中进行初始化,在此您可以通过以下方式获取URL:

        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "yourViewControllerID") as! YourViewController
        vc.url = url
        self.window?.rootViewController = vc

还要在YourViewController文件中,将您的网址设置为:

var url = "" {
    didSet {
       //trigger your webView to start loading, you can also do it at viewDidAppear maybe.
       //example:
       let url = URL(string: url)
       let request = URLRequest(url: url)
       webView.loadRequest(request)
    }
}