OGeek|极客世界-中国程序员成长平台

标题: ios - 按钮不工作取决于变量的长度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:51
标题: ios - 按钮不工作取决于变量的长度

我有一个按钮,当按下它时,它会带你到一个由一些变量组成的 url。除“texto”外,所有变量都是一个词。

如果“texto”是一个词,一切正常。当“texto”超过一个词(甚至是一个词和一个空格)时,问题就来了,并且按钮不会带你到 url。

我的代码如下:

@IBAction func pay(_ sender: Any) {

        NSLog("%@", texto);

        let urlString:String = "https://webpage/video.php?user=\(user)&pass=\(pass)&texto=\(texto)&esp=\(espec)&l_origen=\(l_origen)&l_destino=\(l_destino)"

        if let url = URL(string:urlString){
            let svc = SFSafariViewController(url: url)
            self.present(svc, animated: true, completion: nil)
        }
    } 



Best Answer-推荐答案


正如其他人所说,网址中不允许使用空格。您必须“百分比转义”任何包含空格的字段。但是,您不希望对整个 URL 进行百分比转义,因为这会转义作为 URL 语法一部分的斜杠、冒号和 & 号等字符。

您的代码应如下所示:

@IBAction func pay(_ sender: Any) {

    let escapedTextTo = texto.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    print("texto = ", escapedTextTo);

    let urlString:String = "https://webpage/video.php?user=\(user)&pass=\(pass)&texto=\(escapedTextTo)&esp=\(espec)&l_origen=\(l_origen)&l_destino=\(l_destino)"

    if let url = URL(string:urlString){
        let svc = SFSafariViewController(url: url)
        self.present(svc, animated: true, completion: nil)
    }
} 


请注意,最好使用 URLComponents 创建您的 URL。它会为您处理 URL 各个部分的不同转义规则。

关于ios - 按钮不工作取决于变量的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49255349/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4