-1

How to use NSTimer with data from NSURL pass to NSXMLParser display in TableView

I have application display data from web server by PHP gen' to XML

In my xcode i use NSURL for connect to PHP file (in web server) and use NSXMLParser to read XML data put value to array and final display on TableView

I want to see data in TableView live update or update every x time

I think i can use NSTimer but i don't know how i can where i can put NSTimer to the code in xcode

Christian
  • 25,249
  • 40
  • 134
  • 225
Vasuta
  • 141
  • 1
  • 2
  • 12

1 Answers1

0

In short, something like:

// Schedule a timer repeating every 2 seconds
[NSTimer scheduledTimerWithTimeInterval:2.0
                                 target:self.tableView
                               selector:@selector(reloadData)
                               userInfo:nil
                                repeats:YES];

Longer version:

You need to call -doParse from a timer, fetch data, do parsing, and reload the data.

In order not to block main thread, you must NOT call [[NSXMLParser alloc] initWithContentsOfURL:theURL] from main thread.

Instead:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
      NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
      ...
      // finish parsing
      dispatch_async(dispatch_get_main_queue(), ^{
          [tableView reloadData];
      });
});

And call -doParse with a NSTimer from -viewDidLoad :

[NSTimer scheduledTimerWithTimeInterval:2.0
                                 target:self
                               selector:@selector(doParse)
                               userInfo:nil
                                repeats:YES];

Further reading: WWDC 2012 Session 211 - Building Concurrent User Interfaces on iOS.

ZhangChn
  • 3,154
  • 21
  • 41
  • in my code http://www.vasuta.com/ios/MyLoxFile.zip ... file "MyLoxFileTVContoller.m" i move line 36 to 79 into dispatch_async right? ... where i put dispatch_async in my project? – Vasuta Aug 28 '12 at 04:08
  • http://a7.sphotos.ak.fbcdn.net/hphotos-ak-ash4/480533_522854577730924_988295295_n.jpg – Vasuta Aug 28 '12 at 04:32
  • You have to at least uncomment one of the two `[self.tableView reloadData];` – ZhangChn Aug 28 '12 at 08:37
  • if i use [self.tableView reloadData]; tableview it's not show in my view – Vasuta Aug 28 '12 at 09:11