base64encoded String is showing as nil after using Data(base64encoded: data)

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

Replies

The base64 string must be divided for 4, thus string should be fixed with padding symbol =.

So try to fix your string first, and then decode:
Code Block
extension String {
  var fixedBase64Format: Self {
    let offset = count % 4
    guard offset != 0 else { return self }
    return padding(toLength: count + 4 - offset, withPad: "=", startingAt: 0)
  }
}

I was with the same problem for over a week.

The retrieved base64 from the API is supposed to be a String, but when I was debugging it by printing the received string in the console, I saw that it actually wasn't a String. This is very weird as my variable from my JSONDecoder object is a String, so I was sure it decoded properly.

My original code for decoding that base64 was:

decodeImage(base64: fetchedDocumentDetails.Items[0].Adjunto)

I solved my problem parsing to String that variable that contained the base64 "string" image:

decodeImage(base64: String(fetchedDocumentDetails.Items[0].Adjunto))

Check the type of the variable where you are storing that base64 once it is stored. Be sure to be decoding a string.

I would be interested to know what are you trying to achieve with this code? Are you trying use a good base 64 hash tool for decoding? eg. https://owuk.com/base64-decode.html