Search code examples
swiftfoundationnsjsonserialization

Convert Dictionary to Base64: error Segmentation fault 11


I am trying to create JSON Web Token using JSONSerialization class, Swift 3 and Xcode 8.1, but my project fails to build with error:

Command failed due to signal: Segmentation fault 11.

Anyone knows why my code is not correct?

If I comment out this code from the project, the project builds.

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

Solution

  • Once you create the Data from using JSONSerialization, you simply use the method from Data to get a base64 encoded string.

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

    You can pass different options to base64EncodedString() depending on what format you need the base64 string to be in.