Open Safari from my Today Extension (widget) within my app

后端 未结 2 629
清歌不尽
清歌不尽 2021-01-07 08:47

I have a Today Extension with a text field. I want to use the contents of the text field as a URL to open a browser within my app.

This is my TodayViewController.swi

2条回答
  •  星月不相逢
    2021-01-07 09:03

    You can do this by using deep linking.

    First define a custom URL scheme

    Once your app responds to the custom scheme my-app:// you can open your app from your todayViewController.

    @IBAction func goButton(_ sender: Any) {
    
        let myAppUrl = URL(string: "my-app://openurl/\(yourURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed))")!
        extensionContext?.open(myAppUrl, completionHandler: { (success) in
            if (!success) {
                print("error: failed to open app from Today Extension")
            }
        })
    }
    

    In your app, just like described in the previous link you will have to implement in your app delegate

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

    in this method, the url will be the one you created in your app extension. Meaning it will be my-app://openurl/{the url with percent escaping} You will have to parse this url, initialise the view controller that contains the webView and pass the url to be opened.

提交回复
热议问题