无法使用'#'从字符串创建网址在中间

时间:2017-11-01 19:35:07

标签: swift ios11 tel

通过代码解释问题。

    let u = "tel://*111*11111111111#" //Works perfectly on iOS11 and later
    let u = "tel://*111#11111111111#" //Doesn't work, Can't create URL

    let app = UIApplication.shared
    if let url = URL(string:u) {
        if app.canOpenURL(url) {
            app.open(url, options: [:], completionHandler: { (finished) in 
            })
        }
    }

**如果我对字符串进行编码,则canOpenURL()会失败!

2 个答案:

答案 0 :(得分:1)

只需使用URLComponents即可。处理百分比自动为您和所有事件逃脱。

var comps = URLComponents()

comps.scheme = "tel"
comps.host = "*111#11111111111#"

print(comps.url!) // prints "tel://*111%2311111111111%23"

答案 1 :(得分:0)

问题已修复

数字应该在没有tel://

的情况下单独编码
let u = "tel://*111#11111111111#"
if let encoded = u.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
    let u = "tel://\(encoded)"
    if let url = URL(string:u) {
        if app.canOpenURL(url) {
            app.open(url, options: [:], completionHandler: { (finished) in

            })
        }
    }
}