0

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)
}
Evgeny Karkan
  • 7,517
  • 2
  • 22
  • 35
Maksim Kniazev
  • 3,589
  • 26
  • 34
  • 1
    Of course it freezes if you're downloading data on main thread. Look up how to do it asynchronously. – Michal Jul 25 '16 at 08:15
  • Do I need to use Alamofire? – Maksim Kniazev Jul 25 '16 at 09:18
  • It's handy, because it's the standard way to do it, but in your case it doesn't seem like it. Just look at how dispatch_async functions work and wrap it around your download code. Don't forget to jump up to the main queue when you need to update the UI! – Michal Jul 25 '16 at 09:27
  • Use NSURLSession. An example: http://stackoverflow.com/questions/31264172/how-can-i-get-the-data-from-nsurlsession-sharedsession-datataskwithrequest – Eric Aya Jul 25 '16 at 10:52

2 Answers2

1

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
   });
});
Evgeny Karkan
  • 7,517
  • 2
  • 22
  • 35
0

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..

JAck
  • 788
  • 6
  • 16
  • I throw my NSTimer inside dispatch_async and the app stays frozen – Maksim Kniazev Jul 25 '16 at 11:09
  • No need for using NSTimer.. Instead of NSTimer Try using this 'dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {() -> Void in // time-consuming task' dispatch_async(dispatch_get_main_queue(), {() -> Void in }) – JAck Jul 25 '16 at 11:26
  • will it run only once though? – Maksim Kniazev Jul 25 '16 at 19:38
  • yes It will.. First main queue will be executed and then another wil in background – JAck Jul 26 '16 at 05:54
  • but I need it to execute every 15 sec – Maksim Kniazev Jul 26 '16 at 20:34
  • No problem you can deal with delay... find the time thread on internet and execute.. You have to apply thread concept in your own way.. we can guide you but you are the only who can apply.. please make some research on thread.. – JAck Jul 27 '16 at 05:23