ios - 如何以编程方式打开网址但不能在浏览器中快速打开

标签 ios swift nsurl

当用户单击单元格时,我需要以编程方式打开url,但不需要转至Safari浏览器。需要现场统计。

这个需要模仿post请求

我愿意:

UIApplication.shared.openURL(URL(string: url)!)

但是这个打开的 Safari 浏览器

最佳答案

如果我没记错的话,您想在应用程序本身中打开 URL(无需导航到外部 -Safari- 浏览器)。好吧,如果是这样的话,你应该使用 UIWebView :

You can use the UIWebView class to embed web content in your app. To do so, create a UIWebView object, attach it to a window, and send it a request to load web content. You can also use this class to move back and forward in the history of webpages, and you can even set some web content properties programmatically.

WebViewController:

我建议将 UIWebView 添加到 ViewController(称为 WebViewController)中,并在需要时呈现 ViewController; Storyboard上的 ViewController 应该如下所示:

enter image description here

不要忘记为其分配 Storyboard ID。

和 View Controller :

class WebViewController: UIViewController   {
    @IBOutlet weak private var webVIew: UIWebView!

    var urlString: String?

    override func viewDidLoad() {
        if let unwrappedUrlString = urlString {
            let urlRequest = URLRequest(url: URL(string: unwrappedUrlString)!)

            webVIew.loadRequest(urlRequest)
        }
    }

    @IBAction private func donePressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

用法:

考虑当用户点击另一个 ViewController 中的按钮时您希望显示它:

class ViewController: UIViewController {
    @IBAction private func donePressed(_ sender: Any) {
        let stoyrboard = UIStoryboard(name: "Main", bundle: nil)

        // withIdentifier: the used storyboard ID:
        let webViewController = stoyrboard.instantiateViewController(withIdentifier: "WebViewController") as! WebViewController
        webViewController.urlString = "https://www.google.com/"

    }
}

或者专门针对您的情况(选择一​​个单元格):

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // withIdentifier: the used storyboard ID:
    let webViewController = stoyrboard.instantiateViewController(withIdentifier: "WebViewController") as! WebViewController
    webViewController.urlString = "URL GOES HERE..."
}

希望这有帮助。

关于ios - 如何以编程方式打开网址但不能在浏览器中快速打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41735224/

相关文章:

ios - xctest - 如何测试新 View 是否在按下按钮时加载

ios - Swift 3 JSON 解析异常

objective-c - 在 Objective C 中从 NSDictionary 对象创建 URL 查询参数

ios - 从本地 NSURL 转换 NSData

swift - 初始化 NSURLComponents 实例时将 false 和 true 传递给 'resolvingAgainstBaseURL' 有什么区别?

ios - Xcode 6.3.1、Swift、iOS 8 Interface Builder - 横向时卸载按钮

ios - 解析: fatal error: NSArray element failed to match the Swift Array Element type

ios - 尝试在 Xcode 中使用嵌入式框架会给出 "Use of undeclared type error"

ios - 第二个 View Controller 场景中的 Swift viewDidLoad() 不工作

swift - 苹果 watch http 请求