【问题标题】:replacingOccurrences works in Playground, fails in compiled macos appreplaceOccurrences 在 Playground 中工作,在编译的 macOS 应用程序中失败
【发布时间】:2020-04-16 00:21:50
【问题描述】:

我正在向服务器发送 POST 请求并得到响应。到目前为止,一切都很好。当我将数据转换为(非常长的)字符串时,响应包含反斜杠,它不应该存在。

这是处理请求的sn-p:

   let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let response = response, let data = data {
            print(response)               
            let str = String(data: data, encoding: .utf8)
            let replaced = str?.replacingOccurrences(of: "\\", with: "")
            print(replaced)
        } else {
            print(error)
        }
    }

尝试用

替换“\”字符

让替换 = str?.replacingOccurrences(of: "\", with: "")

在 Playground 中工作,但在调试运行时它不会去除反斜杠。

问题:Xcode 中是否存在错误?在 2018 年的 Xcode 9 中出现了这样的错误。我在 macOS 10.14 上使用 Xcode 11.3 编译 macOS 应用程序。

第二个问题,除了使用之外,还有其他解码数据的方法

            let str = String(data: data, encoding: .utf8)

谢谢

【问题讨论】:

  • “第二个问题,除了使用”还有其他解码数据的方法吗,你的回答是简单的.utf8 编码字符串吗?如果是这样,您当前的解决方案就可以了。
  • 如果let replaced2 = replaced { print("Replaced2: \(replaced2)"}.我认为这可能是因为可选(这只是控制台中的打印,如果您在标签/uitextview 中呈现它,则不一样。所以请进行适当的展开。
  • 你确定字符串包含 real 反斜杠吗?

标签: swift macos backslash


【解决方案1】:

想通了。需要解码数据,而不是编码。

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let response = response, let data = data {
            print(response)                        
            let str = String(decoding: data, as: UTF8.self)
            print (str)


        } else {
            print(error)
        }
    }

【讨论】:

  • 因为str 不是可选的,不是吗?你会用这个let str = String(decoding: dataTest, as: UTF8.self); let str2 = String(data: dataTest, encoding: .utf8); let str3 = String(data: dataTest, encoding: .utf8)! 测试一下吗?提供你的输出会很好。而且它只在控制台中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多