Incorporate a refresh button into the JSON table view that includes an activity

How can I implement a refresh button in my app that displays an activity indicator when pressed?

I have written the following code:

In this app, I am using JSON to retrieve data from a server and I want users to see updated content when they press the refresh button.

Thank you!

// Here is some sample code for implementing a refresh button with an activity indicator

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    // URL for fetching JSON data
    var json_data_url = "http://example/json_table_view_images%20(1).json"
    
    // Base URL for retrieving image resources
    var image_base_url = ""

    // Array to store table data fetched from JSON
    var TableData:Array< datastruct > = Array < datastruct >()

    enum ErrorHandler:ErrorType {
        case ErrorFetchingResults
    }

    struct datastruct {
        var imageurl:String?
        var description:String?
        var image:UIImage? = nil

        init(add: NSDictionary) {
            imageurl = add["url"] as? String
            description = add["description"] as? String
        }
    }

    @IBOutlet var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set data source and delegate for table view
        tableview.dataSource = self
        tableview.delegate = self

        // Fetch data from URL
        get_data_from_url(json_data_url)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        let data = TableData[indexPath.row]

        cell.textLabel?.text = data.description

        if (data.image == nil) {
            // Set default image and load actual image asynchronously
            cell.imageView?.image = UIImage(named:"image.jpg")
            load_image(image_base_url + data.imageurl!, imageview: cell.imageView!, index: indexPath.row)
        } else {
            // Use cached image if available
            cell.imageView?.image = TableData[indexPath.row].image
        }

        return cell

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return TableData.count
    }

    func get_data_from_url(url:String) {

        let url:NSURL = NSURL(string: url)!
        let session = NSURLSession.sharedSession()

        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

        let task = session.dataTaskWithRequest(request) { (let data, let response, let error) in

            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                return
            }

            dispatch_async(dispatch_get_main_queue(), {
                self.extract_json(data!)
                return
            })
        }

        task.resume()
    }

    func extract_json(jsonData:NSData) {
        let json: AnyObject?
        do {
            json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
        } catch {
            json = nil
            return
        }

        if let list = json as? NSArray {
            for (var i = 0; i < list.count ; i++ ) {
                if let data_block = list[i] as? NSDictionary {
                    TableData.append(datastruct(add: data_block))
                }
            }

            do {
                try read()
            } catch {}

            do_table_refresh()
        }
    }

    func do_table_refresh() {
        dispatch_async(dispatch_get_main_queue(), {
            self.tableview.reloadData()
            return
        })
    }

    func load_image(urlString:String, imageview:UIImageView, index:NSInteger) {

        let url:NSURL = NSURL(string: urlString)!
        let session = NSURLSession.sharedSession()

        let task = session.downloadTaskWithURL(url) { (let location, let response, let error) in

            guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
                print("error")
                return
            }

            let imageData = NSData(contentsOfURL: location!)

            dispatch_async(dispatch_get_main_queue(), {
                self.TableData[index].image = UIImage(data: imageData!)
                self.save(index,image: self.TableData[index].image!)

                imageview.image = self.TableData[index].image
                return
            })

        }

        task.resume()
    }

    func read() throws {

        do {
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext = appDelegate.managedObjectContext!
            let fetchRequest = NSFetchRequest(entityName: "Images")

            let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)

            for (var i=0; i < fetchedResults.count; i++) {
                let single_result = fetchedResults[i]
                let index = single_result.valueForKey("index") as! NSInteger
                let img: NSData? = single_result.valueForKey("image") as? NSData

                TableData[index].image = UIImage(data: img!)
            }
        } catch {
            print("error")
            throw ErrorHandler.ErrorFetchingResults
        }
    }

    func save(id:Int,image:UIImage) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext!

        let entity = NSEntityDescription.entityForName("Images", inManagedObjectContext: managedContext)
        let options = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)

        let newImageData = UIImageJPEGRepresentation(image,1)

        options.setValue(id, forKey: "index")
        options.setValue(newImageData, forKey: "image")

        do {
            try managedContext.save()
        } catch {
            print("error")
        }
    }
}

Answer №1

Firstly, ensure that you include two essential steps within the button action. The function 'get_data_from_url()' needs to be called, followed by reloading the tableview using tableview.reloadData().

Implementing these two actions will result in the tableview displaying the latest content accordingly.

Answer №2

If you want to display an activity indicator in the navigation bar,

In Objective-C:

    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicatorView startAnimating];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:indicatorView];

In Swift:

   var myIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
    myIndicatorView.center = view.center
    myIndicatorView.startAnimating()
    var barButtonItem = UIBarButtonItem(customView: myIndicatorView)
    self.navigationItem.rightBarButtonItem = barButtonItem

Now, when you click on the 'refresh' button, use the above code to show the activity indicator on the navigation bar.

Here's a sample Swift class with the above code:

import Foundation

import UIKit

class ViewController: UIViewController {

func addRefreshHeader() {
    let myIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
    myIndicatorView.startAnimating()
    let barButtonItem = UIBarButtonItem(customView: myIndicatorView)
    self.navigationItem.leftBarButtonItem = barButtonItem
} 
}

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

Changing the format of JSON output in Laravel

Help me clean up my JSON output by removing unnecessary elements. This is my current Output: [ { "current_page": 1, "data": [ { "_id": "6580f69587f0f77a14091c22", ...

How to Retrieve Information from a JSON String in an Android App

I am attempting to retrieve data from Github Sample Collection of Books, however, I am encountering a blank screen. Below is the excerpt of my JSON parsing code. try { JSONObject bookObject = new JSONObject(SAMPLE); JSONArray booksArray ...

Tips for changing the JSON result of a method in a WCF service

I'm currently exploring how to customize the name of the JSON object returned from a WCF service to a web client via an AJAX call, rather than using the default wrapper. Despite my efforts, I haven't been able to find any relevant articles on thi ...

Exploring the depths of JSON nested maps in Groovy: a step-by-step guide

I have received the following JSON output from AWS DynamoDB and I am looking to loop through it in order to populate a table within Jenkins Parameters using a Groovy script. Is this achievable? JSON: [ { "test": { "S ...

Issue with loading the schema in the angular.json configuration file

Encountering an issue within the angular.json file that needs attention. { "resource": "/e:/P dev/project/Resume_generator/front/angular.json", "owner": "_generated_diagnostic_collection_name_#1", "c ...

What is the best way to get a server to continuously request a JSON file at regular intervals?

I am currently dealing with updating and displaying real-time information from a third-party JSON file that is approximately 1MB in size. The challenge lies in the fact that this JSON file updates constantly, and my access key may be revoked if users direc ...

Retrieving data with jSON through the local storage API

Seeking assistance with a problem I'm facing. Being new to this, the textbook Headfirst into programming isn't very helpful in explaining. After researching on stackoverflows, I'm still struggling. Any guidance would be greatly appreciated. ...

Unable to retrieve specific key from NSDictionary within FourSquare API venues

I am facing an issue while trying to access the "prefix" and "suffix" strings from the provided FourSquare NSDictionary. Despite attempting different methods in my nsobject, I have not been successful so far. Is there a straightforward way to extract these ...

Implementing a file size restriction in C# when writing a lengthy JSON string using the System.IO.Stream

I have a large array stored in Json format, and the result is saved in a variable called "sz" (string). However, when I attempt to save this Json result (string sz) to a file, it seems that not all of the string gets saved. Why is this happening? The siz ...

How to pass a null parameter with jquery's .ajax method

I am facing the following scenario function AddData(title, id) { $.ajax({ type: "POST", url: "topic.aspx/Add", data: JSON.stringify({ "title": title, "id" ...

The specified message formats required for the operation include 'XML' and 'JSON'

Creating a WCF REST service includes defining methods for adding, deleting, and editing news entities. Here is an example of such a service: [ServiceContract] public interface INewsRepository { [OperationContract] [WebInvoke(Me ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Tips for modifying the value of a JSON object using Javascript or Jquery

I am looking to retrieve the value of a specific key, potentially accessing nested values as well. For example, changing the value of "key1" to "value100" or "key11" to "value111. { "key1": "value1", "key2": "value2", ...

What is the best way to extract a generic class parameter from JSON in Scala?

Has anyone encountered a similar scenario as mine? trait Getter[A] { def get: A } I have defined two implementations of classes that implement this trait: case class CoalesceGetter[A](getters: List[Getter[String]]) extends Getter[A] { override def g ...

I tried implementing a progress bar for my JSON post and response, but unfortunately, it is not displaying as expected

I have successfully implemented JSON data posting to the server. However, I am facing an issue with integrating a progress bar to show the progress. The progress bar is not displaying at all despite the data being posted and response received. @Override ...

How can I enable browser caching for test.json, which is generated by json.php using Apache's rewrite feature?

How can I configure browser caching for test.json, which is generated by json.php? Unfortunately, the response headers for test.json are set as if it were a .php file and not a .json file. How do I correctly apply .htaccess rules so that the generated tes ...

Error encountered while attempting to parse text using JSON

Greetings! I have encountered a JSON object that appears like this: {"messages":["operator will assist you"]} However, when I attempt to parse it using $.parseJSON(json), an unexpected character error occurs, specifically SyntaxError: JSON.parse: unexpec ...

Error: JSON requires string indices to be integers

I need help filtering JSON data from a webhook. Here is the code I am working with: headers = { 'client-id': 'my twitch client id', 'Authorization': 'my twitch oauth key', } params = ( ('query' ...

Developing a JSON object with PHP

Is there a way in PHP to generate the following JSON structure? { "actors": [ { "name": "Brad Pitt", "description": "William Bradley 'Brad' Pitt is an American actor and film producer. He has received a Golden Globe Award, a Sc ...

Are you interested in creating and testing a web service using JSON and C#?

Struggling with creating a JSON WCF web service that connects to MySQL DB on my Server. Feeling quite confused about the whole process! Here's the code I have so far: [ServiceContract] public interface IService1 { [OperationContra ...