【问题标题】:Open web url link in browser in Swift在 Swift 中的浏览器中打开网页 url 链接
【发布时间】:2018-12-06 17:01:05
【问题描述】:

我想加载我通过网络服务获取的链接的网页。我自己试过了,但结果不赞成。

从服务器我得到这种网址: http://www.simrishamn.se/sv/kultur_fritid/osterlens_museum/

我也使用这种类型的代码来加载页面:

let url = URL(string: "http://" + urlSting.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)
UIApplication.shared.openURL(url!)

但是当我在设备中测试这段代码时,它的显示如下:

请帮助加载获取的网址。

编辑: 进行建议的更改后,虽然按钮单击事件正在运行,但不是 Web 浏览器无法打开,请查看下图以获得更多许可:

【问题讨论】:

  • 你的服务器 url 中已经添加了 Http 为什么要在 URL 初始化程序中附加额外的 http
  • 让 url = URL(string: urlSting.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!) UIApplication.shared.openURL(url!)
  • 好吧,让我试试这个......
  • 请检查更新的问题,现在按钮点击不打开网络浏览器...
  • 有什么解决办法吗??

标签: ios iphone swift swift2


【解决方案1】:

你需要检查

喜欢这个

if let url = URL(string: urlSting.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!), UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.openURL(url, completionHandler: nil)
}

还可以尝试删除和/或添加 https:// 前缀,
如果不起作用,则只需执行以下操作:

if let url = URL(string: urlSting), UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.openURL(url, completionHandler: nil)
}

【讨论】:

  • 如果对执行任何单行,我也可以制作 else if 吗??
  • 好的,现在我已经删除了与 https:// 相关的检查,并将两个 if 语句放在 else if 阶梯之上。
  • 大多数情况下,如果通过即不添加PercentEncoding,则应该通过单个来完成,但是如果出现特殊字符或空格,那么如果添加PercentEncoding,您可以再添加一个
【解决方案2】:

请试试这个。

if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
   if #available(iOS 10.0, *) {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
   } else {                                            
      UIApplication.shared.openURL(url)
   }
}

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多