0

A library save a token as Data in UserDefaults

//loading the token
if let token = UserDefaults.standard.object(forKey: "token") as? Data {
 let base64Encoded = token.base64EncodedData
 let base64EncodedString = token.base64EncodedString()
}

When I print that base64Encoded value in the console I get the value: Y2E2N2Y5NTItNDVkOC00YzZkLWFkZDMtZGRiMjc5NGE3YWI2OjdmZDU1ZTAyLWExMjEtNGQ1ZC05N2MzLWM5OWY4NTg5NTIzNg== as Data

When I copy this value from the output in the console and use this website https://www.base64decode.org/ I got the expected result. ca67f952-45d8-4c6d-add3-ddb2794a7ab6:7fd55e02-a121-4d5d-97c3-c99f85895236

My problem is that I don't get convert that base64Encoded to String in my code.

When I use base64EncodedString I got a string, but I can't figure out which format this is: PFsYdirs21247rRG/XcWOVGUGUcCCTzXz7VFAnunLJU= The method base64EncodedString() This is an method from Apple: https://developer.apple.com/documentation/foundation/nsdata/1413546-base64encodedstring

When I decode this value to utf8 at the website I got: <[v*]Fw9QG

When I try to convert my base64Encoded (Data, not String) to a string like this

if let toString = String(data: base64Encoded, encoding: String.Encoding.utf8) as String {
 print("test \(toString)")
}

my compiler threw an error: Cannot convert value of type(Data.Base64EncodingOptions) -> Data to expected argument type Data

Here I found a solution to decode when my Data-value would be a string.
https://stackoverflow.com/a/31859383/4420355

So I'm quite confused about the results. Long story short:

I have base64Encoded Data (Y2E2N2Y5NTItNDVkOC00YzZkLWFkZDMtZGRiMjc5NGE3YWI2OjdmZDU1ZTAyLWExMjEtNGQ1ZC05N2MzLWM5OWY4NTg5NTIzNg==) and want them convert to an utf8 string. I don't get handle this.

kuzdu
  • 7,124
  • 1
  • 51
  • 69
  • so where do you get the correct result which you copy from debug? in which property you have this? – haik.ampardjian Jun 12 '17 at 16:38
  • where does deviceToken come from? this is confusing to read. it looks like you are taking data. base64 encoding the data, then trying to read the base64encoded data as data. you need to decode it first and then read it with string(data: data, encoding: String.Encoding.utf8) – Scriptable Jun 12 '17 at 16:43
  • Im sorry, i edited my question. I read Data and get the right result in token.base64EncodedData but this data I need to change in a UTF8 string – kuzdu Jun 12 '17 at 17:31

0 Answers0