简体   繁体   English

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

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

I have a Today Extension with a text field. 我有一个带有文本字段的Today Extension。 I want to use the contents of the text field as a URL to open a browser within my app. 我想使用文本字段的内容作为URL在我的应用程序中打开浏览器。

This is my TodayViewController.swift for my widget 这是我的小部件的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")
        }
    })
}

You could use @Giuseppe_Lanza solution and parse url that you receive from Today Extension Widget. 您可以使用@Giuseppe_Lanza解决方案并解析从Today Extension Widget收到的URL。 However, I would show an example where your url have a static components and looking for a path such as https:/www.apple.com/homepod or https:/www.apple.com/iphone based on user's input in the textField: 但是,我将显示一个示例,其中您的url具有静态组件,并根据textField中用户的输入来查找诸如https:/www.apple.com/homepodhttps:/www.apple.com/iphone类的路径:

1- URL Scheme: myAppName 1- URL方案: myAppName

2- Add this to open your app with widget 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 3- AppDelegate

Define a variable and pass received url to webViewController, will parse url there. 定义一个变量并将接收到的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)
}

Make sure to make add an identifier for this segue under the attributes inspector as toDeepLink . 确保在属性检查器下添加此toDeepLink的标识符为toDeepLink

4- WebView & parsing url Now you can get the receivedUrl like this 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)
}

Else, you need to parse it in a proper way like dictionary to assign dynamic values to respective keys in your dictionary and hence to your url or append "?" 否则,您需要以适当的方式(例如字典)对其进行解析,以将动态值分配给字典中的各个键,从而分配给您的url或附加"?" to your urlToLoad just before you attempt to append url.query as I did in the webView controller. 就像我在webView控制器中一样尝试将url.query附加到urlToLoad之前。

You can do this by using deep linking. 您可以通过使用深层链接来实现。

First define a custom URL scheme 首先定义一个自定义URL方案

Once your app responds to the custom scheme my-app:// you can open your app from your todayViewController. 一旦您的应用程序对自定义方案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")
        }
    })
}

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. 这意味着它将是my-app://openurl/{the url with percent escaping}您将必须解析该网址,初始化包含webView的视图控制器,然后传递要打开的网址。

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

相关问题 如何使用Swift在我的应用程序的“今日扩展”中的Safari中打开url - How to open a url in Safari from my Today Extension within my app using Swift 在我的iOS应用程序中从Safari打开具有特定扩展名的文件 - Open file with specific extension from Safari in my iOS app 使用我的应用程序中的“打开方式”从Safari打开文件 - Open files from Safari with “Open in” in my app iOS Today Extension:可以在我的应用程序中动态启用和禁用吗? - iOS Today Extension: can this be dynamically enabled and disabled from within my app? 今日应用扩展小部件点击以打开包含应用 - Today App Extension Widget Tap To Open Containing App 如何打开我的 SwiftUI 应用程序并使用 Siri Intent Extension 中的 NSUseractivity 执行功能? - How can I open my SwiftUI app and perform a function using NSUseractivity from within Siri Intent Extension? iOs - 如何使用url将数据从Widget(今日扩展)传递到App? - iOs - How to pass data from Widget (Today Extension) to App with url? 如何通过我的网络视图应用打开safari中的.pdf文件 - how to open .pdf files in safari from my web view app 从Safari在我的iPhone应用程序中打开GPX文件 - Open a GPX file in my iPhone app, from Safari 如何从包含的应用程序更新我的iOS Today小部件? - How can I update my iOS Today widget from the containing app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM