I'm trying to get the readme data for a selected repository from the GitHub api. So, the "content" is the content of the readme file, but is a base64 type. I tried to convert it but when I'm running the app, I get a fatal error "Fatal error: Unexpectedly found nil while unwrapping an Optional value "
Code:
class DetailsViewController: UIViewController {
var details: Item?
var read: Readm?
@IBOutlet weak var forksLabel: UILabel!
@IBOutlet weak var starLabel: UILabel!
@IBOutlet weak var readMeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
forksLabel.text = "\(details!.forks_count)"
starLabel.text = "\(details!.stargazers_count)"
downloadJSON {
return
}
readMeLabel.text = decodeBase64(word: read!.content) // <- here is the error
}
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()
}
func decodeBase64(word: String) -> String {
let base64Decoded = Data(base64Encoded: word)!
let decodedString = String(data: base64Decoded, encoding: .utf8)!
return decodedString
}
}
This is where the error is :
readMeLabel.text = decodeBase64(word: read!.content)
EDITED:
super.viewDidLoad()
forksLabel.text = "\(details!.forks_count)"
starLabel.text = "\(details!.stargazers_count)"
downloadJSON {
if let content = self.read?.content {
self.readMeLabel.text = self.base64Decoded(word: content)
print(self.base64Decoded(word: content))
}
}
}
func base64Decoded(word: String) -> String? {
guard let base64Data = Data(base64Encoded: word) else { return nil}
let decodedData = String(data: base64Data, encoding: .utf8)
return decodedData
}
I have managed how to unwrap things, but now, my label is empty, I made a print statement and is nil. Anyone know why ?