Base 64 decoded, value is nil

I’m trying to decode a base64 type to String, but the content is always nil.
There is how im getting the data from the json.

func downloadJSON (completed: @escaping () -> ()) {
    let url = URL (string: "https://api.github.com/repos/\(details!.full_name)/readme")
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error == nil {
            do {
                print("ceva")
                self.read = try JSONDecoder().decode(Readm.self, from: data!)
                DispatchQueue.main.async {
                    completed()
                }
            } catch {
                print (error)
            }
            
        }
    }.resume()
}

Here is my func base64, I put a breakpoint at the return String, but the code is never executed , probably goes on the branch " return nil"

func base64Decoded(word: String) -> String? {
    guard let base64Data = Data(base64Encoded: word) else { return nil}
    return String(data: base64Data, encoding: .utf8)
}

This is how I’m doing the call

downloadJSON {
    if let content = self.read?.content {
        self.readMeLabel.text = self.base64Decoded(word: content)
    }
}

Is the JSON data nil? Does this line run correctly?

self.read = try JSONDecoder().decode(Readm.self, from: data!)

Where is base64Decoded being run at? It looks like just another function but I don’t know where it fits into your entire code

Also you’re taking a string, turning it into data and then back to a string? Why? That doesn’t make sense

Looking at the response from that API call, content contains some newline characters \n. Those can cause problems, per Apple’s docs:

The default implementation of this method will reject non-alphabet characters, including line break characters.

So try using this instead:

Data(base64Encoded: word, options: .ignoreUnknownCharacters)
1 Like

Yep, that was the problem. Thank you very much !