replacingOccurrences在Playground中有效,在编译的macos应用程序中失败



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

">

以下是处理请求的片段:

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)
}
}

尝试用替换"\"字符

让replaced=str?。replacingOccurrences(of:"\",with:"(

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

问题:Xcode中有漏洞吗?2018年,Xcode 9出现了这样一个错误。我在macOS 10.14上使用Xcode 11.3编译macOS应用程序。

第二个问题,除了使用,还有其他方法可以解码数据吗

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

感谢

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

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)
}
}

相关内容

最新更新