在我的应用程序中从我的今日扩展(小部件)打开Safari [英] Open Safari from my Today Extension (widget) within my app

查看:89
本文介绍了在我的应用程序中从我的今日扩展(小部件)打开Safari的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的小部件的TodayViewController.swift

This is my TodayViewController.swift for my widget

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。但是,我会展示一个示例,其中您的网址包含静态组件并查找路径,例如 https:/www.apple.com/homepod https://www.apple.com/iphone 根据用户在textField中的输入:

You could use @Giuseppe_Lanza solution and parse url that you receive from Today Extension Widget. 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:

1- URL方案: myAppName

1- URL Scheme: myAppName

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

2- Add this to open your app with widget

这篇关于在我的应用程序中从我的今日扩展(小部件)打开Safari的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆