Yaroslav Dukal
Yaroslav Dukal

Reputation: 3942

Parsing JSON freezes tableView SWIFT

My current problem is that when the function updateLabels is called my tableView freezes. My goal is to update radio stations song names and titles every 15 seconds. I have a dict array that holds the info and the function that populates that dict array every 15s. Each station has a separate JSON link file that I put into my getData function parameters. What can I do to make it better and stop tableView to freeze?

main array

var songNames = [
                (songArtist: "", songName: ""),
                (songArtist: "", songName: ""),
                .....
            ]

update songs title and names

func updateLabels() {
    songNames.removeAll()   
    songNames.append((songArtist: getData("rd").artistName, songName: " - \(getData("record").songName)"))
    songNames.append((songArtist: getData("mix").artistName, songName: " - \(getData("mix").songName)"))
    tableView.reloadData()
}

get data from JSON link

func getData(urlPart: String) ->(artistName: String, songName: String) {
    let mainURl = "http://...json"
    let url = NSURL(string: mainURl)
    let jsonData = NSData(contentsOfURL: url!) as NSData!
    let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error:  nil)
    let songArtistName = readableJSON["ARTIST"]
    let songName = readableJSON["NAME"]                
    return (songArtistName.description, songName.description)
}

in my viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    updateLabels()
    //**Timer to call the function every 15 sec**
    NSTimer.scheduledTimerWithTimeInterval(15, target: self, selector: #selector(self.updateLabels), userInfo: nil, repeats: true)
}

Upvotes: 0

Views: 165

Answers (2)

Evgeny Karkan
Evgeny Karkan

Reputation: 9662

Well, the main problem is because you are getting JSON data on the main thread, that is why UI freezes. Instead of doing it on the main thread you should dispatch this task async on background thread.

At the end of async background task, iOS SDK will switch program flow to the main thread, where you must update your UI components with fetched JSON data.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

   // Get JSON data here

   dispatch_async(dispatch_get_main_queue(), ^{
       // Update UI here
   });
});

Upvotes: 1

JAck
JAck

Reputation: 864

Try using threading / Grand Central Dispatch If you don't know it. Just do like..

dispatch_async(dispatch_get_main_queue(), {() -> Void in

//call your function here..

})

If it's not resolving just comment below.. I will help..

Upvotes: 0

Related Questions