Tips for converting a base64 encoded string to a normal string in Swift

Obtaining the readme data for a selected repository from the GitHub api has proven to be a challenge. The "content" seems to be in base64 format, and while attempting to convert it I encountered a fatal error: "Fatal error: Unexpectedly found nil while unwrapping an Optional value".

Here is the code snippet:

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 section contains the problematic line:

readMeLabel.text = decodeBase64(word: read!.content)

A recent update includes:

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 successfully resolved the unwrapping issue, but now my label remains empty. After adding a print statement, I discovered that it returns nil. Any insights as to why?

Answer №1

Utilize the existing asynchronous completion handler without hesitation.

Instead of a singular return statement, place the line within the closure for better functionality.

Always handle value unwrapping with caution to prevent potential errors.

downloadJSON {
    if let data = self.read?.data {
        self.displayLabel.text = self.base64Decode(input: data)
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The string retrieved from the server is showing special characters as "?"

I am facing an issue with my servlet where it retrieves data from Cloud SQL, converts it to a Java object, and then converts it to JSON before appending it to the response writer. The problem arises when the data contains special characters like "ç" and ...

Getting the URL for a downloaded image using ImageLoad on Android

I encountered an issue with my Android application In the database, I stored URLs of some images and now want to download these images for a viewpager display using ImageLoader. The problem arises when trying to download the image URLs from the server. I ...

What is the process for combining two values from a JSON-array in a specific sequence?

Currently, I am utilizing PostgreSQL 9.5 and have a table containing JSON arrays with JSON objects structured like so: [] [{animal:cat}, {plant:sunflower}, {car:mercedes}] [{animal:dog}] [{animal:dog}, {car:audi}] [] The goal is to present a table that m ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

Connecting different domains using AJAX

Is it possible to send an Ajax request to a separate server instance (running on a different port) on the same machine? ...

Having trouble with missing quotes in Swift when making a REST POST request

Struggling with a seemingly simple REST call that has left me completely stuck. I have a node-based restful service that requires an array of strings as input. However, every time I make the call with what seems like a valid parameter, the server throws an ...

Use the `DefaultValue` feature on all string properties during serialization

Make sure to set DefaultValue for all string properties. Situation: The classes below are automatically generated, making it tedious to manually add properties. To simplify the process, I created a program that uses regex to add the necessary properties ...

My GraphQL Query is throwing a JSON error when using the curlopt_postfields option. What could be causing this

I'm having some trouble with my code and I keep encountering this error message. Any ideas on what might be causing this issue? I believe I've properly escaped all the quotations. {"errors":[{"message":"json body could ...

Use regex to convert a JSON object into a string representation of an SMT connector

Imagine a message on a Kafka topic, event: { "x":1, "y":2, "c": "abc"}. I want to transform the event object into event: "{\"x\": 1, \"y\":2, \"c\":&bs ...

The JSON data is being posted, but the table remains empty and does not populate

UPDATE: Tried modifying the Jquery code to dynamically recreate rows, but it still doesn't work Reorganized my table structure with no success I have a PHP script that encodes my database table into an array. When I echo the json_encode, everything ...

Data fields in BigQuery are automatically converted for ease of use

Insight When uploading JSON data to a BigQuery table with autodetect enabled, I encountered an issue where the field "a" could not be converted to an integer. Upon further investigation and modification of the JSON data, changing values in the "a" field ...

Changing a Unique JSON Structure into a VB.NET Object

I have a JSON object that is structured as follows. { "Errors":{ "err1":[ //* Array of err1 objects ], "err2":[ //* Array of err2 objects ] } } This object is used to report errors identified in a request to a PHP page. My goal i ...

Receiving an incorrect UTF-8 sequence in the JSON input

I currently have an ec2 server running with PHP version 5.3, hosting 2 virtual hosts: one for development and one for live production. Interestingly, on the development host, if someone uploads a file containing invalid UTF-8 characters, it simply ignores ...

Tips for preserving a collection of items in a thesaurus?

My project involves a Python 3.5 program that manages an inventory of various objects. One key aspect is the creation of a class called Trampoline, each with specific attributes such as color, size, and spring type. I frequently create new instances of thi ...

Sending JSON data from a Django view to a JavaScript function

I am trying to pass JSON data to JavaScript. I need the JSON structure to be like this: data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database ...

Is it possible for additional JSON properties to be deserialized into a JObject within a class during the deserialization process?

Imagine we are working with the following JSON data: { "apple": 5, "banana": "yellow", "orange": 10, "grape": "purple", } and a C# class is defined as: class Fruits { public int AppleCount { get; set;} public string BananaColor ...

Utilizing numerous JSON entities within an AS3 socket

When receiving JSON data from a camera through a Socket, I encountered an issue. The received data contains two JSON objects in the socket. Is there a way to separate them before decoding? This is the error message I receive when trying to decode the J ...

JSON reorders the elements in a different sequence

Currently, I am facing an issue while attempting to transfer a list of objects from an android mobile phone application to a j2ee webserver. To achieve this, I create JSON objects, place them in a JSONArray in a specific order, and then send it over. Upon ...

Sending a request via AJAX to retrieve a complicated object

Programming Environment: ASP.NET, jQuery Below is the AJAX call I am using: var tempVar = JSON.stringify({plotID:currentId}); $.ajax({ type: "POST", url: "testPage.aspx/getPlotConfig", data: tempVar, contentType: ...

Leveraging Grid and Proxy to access and store information using a single URL in ExtJS 4

I'm a bit confused about how proxies work in ExtJS. Is it possible to use basic functions with them to both retrieve and store data using just one URL? For instance, can I call users.read() to fetch data and users.save() to save new or edited grid fie ...