I have an app where I need to connect to a web API. I have the code written out and working for connecting. My problem starts as soon as I get the response from the web API. I am getting a base64encoded string back from the web API, and I can print that string out and decode it in an online decoder and it is correct, but as soon as I pass that data into Data(base64encoded: data) it is coming out as nil. It makes no sense at all and I can't seem to figure out why it would be nil.
Here is the code I have right now...
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
do {
print("Data as a string: ", String(data: data!, encoding: .utf8) ?? "NONE AVAILABLE")
let decodedData = Data(base64encoded: data!)
print("DECODED DATA: ")
print(decodedData as Any)
let apiResponse = try JSONDecoder().decode(ApiConnectionResponse.self, from: decodedData!)
completion(.success(apiResponse))
} catch {
completion(.failure(error))
}
}.resume()
So the output of that is...
Data as string: eyJzdWNjZXNzIjoiZmFsc2UiLCJlcnJvciI6Im1vYmlsZV9waW5fY29ubmVjdDogaW52YWxpZCBvciBleHBpcmVkIn0.
DECODEDDATA:
nil
As you can see, the "Data as a string: ..." is showing a correctly formatted base64encoded string, that will decode to the correct data I need. The problem is as soon as I run that through Data(base64encoded: data!) it is nil.
It makes ne sense to me at all, can anyone help me out? I am pretty lost, and asking on stack overflow has not produced any help either.
I am more than happy showing more of the code if that is what is needed, I just don't understand why it is correct as a string, but nil as Data.
Thank you