繁体   English   中英

从我的应用程序中的“今日扩展”(窗口小部件)打开Safari

[英]Open Safari from my Today Extension (widget) within my app

我有一个带有文本字段的Today Extension。 我想使用文本字段的内容作为URL在我的应用程序中打开浏览器。

这是我的小部件的TodayTodayViewController.swift

import UIKit
import SafariServices
import NotificationCenter

// This extension to remove the white spaces from what pasteed   
extension String {
func replace(string:String, replacement:String) -> String {
    return self.replacingOccurrences(of: string, with: replacement,             
options: NSString.CompareOptions.literal, range: nil)
}

func removeWhitespace() -> String {
    return self.replace(string: " ", replacement: "")
}
}


class TodayViewController: UIViewController, NCWidgetProviding {

var clearNumber: String?

override func viewDidLoad() {
    super.viewDidLoad()

}


func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
    // Perform any setup necessary in order to update the view.

    // If an error is encountered, use NCUpdateResult.Failed
    // If there's no update required, use NCUpdateResult.NoData
    // If there's an update, use NCUpdateResult.NewData

    completionHandler(NCUpdateResult.newData)
}



@IBOutlet weak var textBox: UITextField!

@IBAction func clearNumber(_ sender: Any) {

    if textBox.hasText == true {
        textBox.text = ""
    }else{
        return
    }

}

@IBAction func pasteNumber(_ sender: Any) {

    if let myString = UIPasteboard.general.string {
        let pasteNumber = myString.removeWhitespace()
        textBox.insertText(pasteNumber)
    }else{
        return
    }
}

@IBAction func goButton(_ sender: Any) {

    let myAppUrl = URL(string: "main-screen:")!
    extensionContext?.open(myAppUrl, completionHandler: { (success) in
        if (!success) {
            print("error: failed to open app from Today Extension")
        }
    })
}

您可以使用@Giuseppe_Lanza解决方案并解析从Today Extension Widget收到的URL。 但是,我将显示一个示例,其中您的url具有静态组件,并根据textField中用户的输入来查找诸如https:/www.apple.com/homepodhttps:/www.apple.com/iphone类的路径:

1- URL方案: myAppName

2-添加它以使用小部件打开您的应用

@IBAction func goButton(_ sender: Any) {
    openApp(widgetText: "\(textBox.text!)")
}

func openApp(widgetText:String)    {

    let str = "myAppName://https://www.apple.com/\(widgetText)"
    let url = URL(string: str)!
    if textBox.hasText == true  {

        extensionContext?.open(url, completionHandler: { (success) in
            if (!success) {
                print("error:  🧐")
            }
        })
    }
}

3- AppDelegate

定义一个变量并将接收到的URL传递给webViewController,将在那里解析URL。

open var receivedUrl:URL?

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

    receivedUrl = url
    //You need to alter this navigation to match your app requirement so that you get a reference to your previous view..
    window?.rootViewController?.performSegue(withIdentifier: "toDeepLink", sender: nil)
}

确保在属性检查器下添加此toDeepLink的标识符为toDeepLink

4- WebView和解析URL现在,您可以像这样获取ReceivedUrl

    override func viewDidLoad() {
    super.viewDidLoad()

    let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
    print("receivedUrl \(myAppDelegate.receivedUrl!)")
    //url Parsing & getting rid off urlScheme
    let urlToLoad = URL(string: "\(myAppDelegate.receivedUrl!.host! + ":" + myAppDelegate.receivedUrl!.path)")!
    print(urlToLoad)
    let urlRequest = URLRequest(url: urlToLoad)
    webView.load(urlRequest)
}

否则,您需要以适当的方式(例如字典)对其进行解析,以将动态值分配给字典中的各个键,从而分配给您的url或附加"?" 就像我在webView控制器中一样尝试将url.query附加到urlToLoad之前。

您可以通过使用深层链接来实现。

首先定义一个自定义URL方案

一旦您的应用程序对自定义方案my-app://做出响应,您就可以从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")
        }
    })
}

在您的应用程序中,就像上一个链接中所述,您将必须在应用程序委托中实现

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

在这种方法中,网址将是您在应用扩展程序中创建的网址。 这意味着它将是my-app://openurl/{the url with percent escaping}您将必须解析该网址,初始化包含webView的视图控制器,然后传递要打开的网址。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM