【问题标题】:convert a string to google searchable string in swift [duplicate]快速将字符串转换为谷歌可搜索的字符串[重复]
【发布时间】:2018-10-24 14:25:35
【问题描述】:

我想为任何给定的字符串打开谷歌搜索,这是我的代码,但它没有打开对给定字符串的搜索。

let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?"
let search = s.replacingOccurrences(of: " ", with: "+")



if let url = URL(string: "https://www.google.com/search?q=\(search)"), NSWorkspace.shared.open(url) {
        print("default browser was successfully opened")

    }

【问题讨论】:

    标签: swift url search


    【解决方案1】:

    字符串中还有其他字符需要正确转义,而不仅仅是空格。

    let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?"
    let search = s.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    
    if let search = search, let url = URL(string: "https://www.google.com/search?q=\(search)"), NSWorkspace.shared.open(url) {
        print("default browser was successfully opened")
    } else {
        print("Can't create search URL with \(search)")
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-20
      • 1970-01-01
      • 2016-07-29
      • 2013-01-06
      • 2015-06-19
      • 2015-04-09
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      相关资源
      最近更新 更多