UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

BASE64 DECODED CONTENT IS NIL

Forums > Swift

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

2      

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)

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.