swift 3 : Converting Data to String returns a nil value

标签 swift

将数据转换为字符串返回 nil 值。

代码:

// thus unwraps the image
if let image = image{
        print("Saving image data")

    // don't unwrap here
        if let data = UIImagePNGRepresentation(image){ 
            let str = String(data: data, encoding: .utf8)

            print(str)

        }
    }

我不知道原因。 另外,如何将字符串转换回数据?

最佳答案

这不起作用,因为当您将图像的字节解释为字符串时,该字符串无效。并非每个困惑的数据都是有效的 utf8 字符串。也就是说,并非每个 n 位(8 位,有时是 16 位)的集合都是有效的 utf8 代码点。 Swift String api 循环遍历您传递给它的数据对象,以验证它是一个有效的字符串。在您的情况下,没有理由认为此 Data 是有效字符串,因此它不起作用。

关于 utf8 的好读物: https://www.objc.io/issues/9-strings/unicode/

关于 swift 3 : Converting Data to String returns a nil value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111455/

相关文章:

swift - 如何在 Swift 中模拟 UIApplication?

ios - 在 SwiftUI 中管理 View 层次结构

swift - UIsearchController 没有成为 ios 9 中的第一响应者

ios - 从带有 html 正文和图像标签的 iOS 应用程序发送电子邮件

ios - 如何快速获取控制台中出现的错误消息以在 UI 中进行验证?

ios - AVAudioPlayerNode 完成处理程序计时

ios - 适用于 iOS 的 Elasticsearch 客户端

ios - 点击按钮执行某些操作,然后转到另一个 View Controller

ios - 当以编程方式设置 Root View Controller 时,导航和选项卡栏丢失

swift - HTTP GET 请求时出现 Cloudant 函数子句错误