Converting a JSON image string (not a URL) into a UIImage to display

After spending an entire day trying to solve this, I am really desperate for an answer. It seems like a simple task - I have a JSON array of images in the form of strings (I believe). These are not URLs, but rather image file names like "GoodLogo.png". Typically, images from JSON come in URL format, but I'm dealing with just the file extensions.

This is the JSON data I receive:

(
    {
    id = 1;
    logo = "scriptslogo.png";
    name = "scripts";
},
    {
    id = 2;
    logo = "altrlogo.jpg";
    name = "Altr";
},
    {
    id = 3;
    logo = "bostonlogo.jpeg";
    name = "Boston";
},
)

I have a variable that holds an array of strings where I store this JSON data.

Code:

    var imageList = [String]()

    let urlString = "https://some.url/api"

    if let url = NSURL(string: urlString) {

        let request = NSMutableURLRequest(url: url as! URL)
        
        request.httpMethod = "GET"
        
        let session = URLSession.shared
        
        let task = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
            
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray {
                
                let logos = jsonObj.value(forKey: "logo") as? NSArray
                self.imageList = logos as! [String]
                
                DispatchQueue.main.async {
                    self.imageTableView.reloadData()
                }
            }
            
        }
        task.resume()
    }

Now, my challenge is populating a table view with these images, but every approach I've tried either crashes the application or displays nothing.


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        var cellReuseID = ""
        
        if tableView == imageTableView {
            
            cellReuseID = "imageCell"
            
            let cell = imageTableView.dequeueReusableCell(withIdentifier: cellReuseID, for: indexPath) as! ImageCell
            
            let imageName = imageList[indexPath.row]

            // Attempting to convert the string to an image
            if let imageData = Data(base64Encoded: imageName, options: .ignoreUnknownCharacters) {
                let image = UIImage(data: imageData)
                cell.cellImage.image = image
            }
            
            return cell
        }
        
       return UITableViewCell()
    }

Answer №1

Give This a Shot

let urlString = "http://example.com/pictures/\(selectedImages[indexPath.row])"
if let url = URL(string: urlString) {
    if let imageData = try? Data(contentsOf: url) {
        cell.imageView.image = UIImage(data: imageData)
    }
}

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

Reading a file in pyspark that contains a mix of JSON and non-JSON columns

Currently, I am faced with the task of reading and converting a csv file that contains both json and non-json columns. After successfully reading the file and storing it in a dataframe, the schema appears as follows: root |-- 'id': string (null ...

The WCF Service is experiencing issues when attempting to call a client for accessing REST with JSON, as the correct content type is

I've been struggling with a perplexing issue for the past few days - I'm trying to utilize a WCF service to call another RESTful service. However, as I trace through the process, it consistently fails to set the appropriate JSON content type on ...

Invalid entry detected in JSON object

I developed a code to deserialize the JSON data from this API To start off, I created a class structure: public class Self { public string href { get; set; } } // Other class definitions omitted for brevity... public class RootO ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

How to utilize the WHERE clause on an array or a JSON encoded value

The values are stored under the company_id field, such as: ["2"] ["2", "1"] In this case, 2 and 1 are the IDs of different companies. Now I am interested in retrieving all the results for the company with ID 2. How can I query the JSON encoded data to ac ...

Developing a custom JsonMediaTypeFormatter for a Webapi platform

I'm currently working on developing a custom JSONMediaTypeFormatter to send some JSON parameters to a web API endpoint. The goal is to encrypt the data returned from the web API, which requires creating a customized media type formatter. Within my we ...

When using flask.jsonify, the output is wrapped in square brackets, as opposed to the usual curly

I'm currently facing an issue with my Flask and jsonify setup. When I try to output JSON, it's coming back in array format with square brackets instead of the expected JSON object with curly brackets. Does anyone have guidance on how to resolve ...

When trying to export a JSON file from an Angular app, the URL is prefixed with 'unsafe' and the download fails with a network error message

Looking for guidance on exporting a JSON file from an angular app. Below is the code snippet I am using: app.js file: app.config(['$compileProvider', function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(htt ...

Python Elastic Reindex: issue with field [source] parsing encountered

I have been attempting to reindex an index using a Python function like this: resp = client.reindex( body={ "source": { "remote": {"host": "url_name:9200","username": &qu ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...

Can you provide a visual representation of the JSON structure?

$data = array('name'=>'John', 'age'=>25, 'city'=>'New York'); I am practicing my PHP skills by using cURL for making a POST request. Assuming the given array is converted into JSON format, what wo ...

Change the range into a JSON array

How can I create a custom function in Excel VBA to convert a range into a JSON array? Currently, I only have the function signature: Function to_json(input As Range) End Function I need the input to be converted into a JSON array with the following stru ...

Extracting PNG file from response (bypassing standard JSON extraction)

Despite my efforts to find a solution, I am still unable to resolve this specific issue: I have implemented an Angular request (localhost:4200) to an API on Spring (localhost:8080). The HttpService successfully handles the requests, except when it comes to ...

What is the best way to iterate over an array of objects?

I have an Array of Objects that I need to use in order to create an HTML Table: Array(5) 0: Object id: 4 name: Sand Jane address: Green Sand Street ... ... ... 1: Object 2: Object ... ... ... Currently, I am able to perform a search wit ...

Extract JSON encoded data in Codeigniter

I have been utilizing the codeigniter framework along with the REST_Controller library. Previously, I relied on $this->input->post() to retrieve values from POST requests. However, some values are transmitted in the body as a json encoded string, wh ...

Jinja: generating recursive json outputs

I am having trouble rendering this specific json object using the jinja template engine view full json object here Shortened version: { "data": { "domain.org": { "type": "folder", "children&q ...

What is the best way to convert items from a foreach loop into a JSON string using the json_encode() function in PHP?

I want to populate a string with all the emails fetched from the database, in order to use JavaScript for checking if the email entered by a user in a form field is already registered. I'm attempting to utilize the json_encode() function. $connec ...

Decoding Json data in C# using JSON.NET

I am currently working on a C# application that retrieves the backpack value of players in a game called TF2 using Backpack.tf's API. Here is a snippet of the code: (MAIN CLASS) JsonConvert.DeserializeObject<Json1>(json); (END OF MAIN CLASS) ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...