2016-11-16 40 views
0

我試圖用JSONSerialization類,斯威夫特3和的Xcode 8.1,創建JSON網絡令牌,但我的項目構建失敗,錯誤:轉換詞典爲Base64:錯誤分段故障11

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

回答

0

一旦你使用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") 
} 

您可以根據您需要的字符串的base64什麼格式是在通過不同的選項base64EncodedString()