将字典转换为 Base64:错误分段错误 11

Convert Dictionary to Base64: error Segmentation fault 11

我正在尝试使用 JSONSerialization class、Swift 3 和 Xcode 8.1 创建 JSON Web 令牌,但我的项目无法构建错误:

Command failed due to signal: Segmentation fault 11.

有人知道为什么我的代码不正确吗?

如果我从项目中注释掉这段代码,项目就会生成。

 let customerError = "Custom Error"
 enum headerError: Error {
 case customerError
 }

 let headerJWT: [Dictionary] = ["alg":"RS256","typ":"JWT"]

 //Convert headerJWT to Data
 do {
    let headerJWTData: Data = try? JSONSerialization.data(withJSONObject:headerJWT,options: JSONSerialization.WritingOptions.prettyPrinted) 
 } catch headerError.customerError {
        print("could not make data")
 }

 //Convert headerData to string utf8
 do {
    let headerJWTString = try String(data: headerJWTData,encoding:String.Encoding.utf8) as! String
 } catch {
     print("string could not be created")
 }

 //Convert headerJWTString to base64EncodedString
 do {
    let headerJWTBase64 = try Data(headerJWTString.utf8).base64EncodedString()
 } catch {
"base64 could not be created"
 }

使用 JSONSerialization 创建 Data 后,您只需使用 Data 中的方法即可获取 base64 编码字符串。

let headerJWT: [Dictionary] = ["alg":"RS256","typ":"JWT"]

do {
    let headerJWTData: Data = try? JSONSerialization.data(withJSONObject:headerJWT,options: JSONSerialization.WritingOptions.prettyPrinted)
    let headerJWTBase64 = headerJWTData.base64EncodedString()
} catch headerError.customerError {
    print("could not make data")
}

您可以将不同的选项传递给 base64EncodedString(),具体取决于您需要 base64 字符串的格式。