PFQueryTableView Auto Refresh When New Data Update

2020-07-26 16:09发布

问题:

Currently Im following this tutorial http://www.appcoda.com/ios-programming-app-backend-parse/

But I want the tableviewcontroller to be refresh with new data when data from parse.com is update automatically. I don't want the user to always have to pull to refresh.

or maybe having time refresh every minute?

I heard about reloaddata but how to implement the code?

- (id)initWithCoder:(NSCoder *)aCoder
{
 self = [super initWithCoder:aCoder];
 if (self) {
     // The className to query on
     self.parseClassName = @"Recipe";

     // The key of the PFObject to display in the label of the default cell style
     self.textKey = @"name";

     // Whether the built-in pull-to-refresh is enabled
     self.pullToRefreshEnabled = YES;

     // Whether the built-in pagination is enabled
     self.paginationEnabled = NO;
 }
 return self;
}

- (PFQuery *)queryForTable
{
 PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

 return query;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
 static NSString *simpleTableIdentifier = @"RecipeCell";

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
 if (cell == nil) {
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
 }

 // Configure the cell
 PFFile *thumbnail = [object objectForKey:@"imageFile"];
 PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
 thumbnailImageView.image = [UIImage imageNamed:@"placeholder.jpg"];
 thumbnailImageView.file = thumbnail;
 [thumbnailImageView loadInBackground];

 UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
 nameLabel.text = [object objectForKey:@"name"];

 UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
 prepTimeLabel.text = [object objectForKey:@"prepTime"];

 return cell;
}

回答1:

In .h file

@property (nonatomic, strong) NSTimer *fetchTimer;
@property (nonatomic, strong) NSArray *items;

In .m file

- (void)viewDidLoad
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:3600
                                             target:(id)self
                                           selector:@selector(fetch)
                                           userInfo:nil
                                            repeats:YES];
    self.fetchTimer = timer;
}

- (void)fetch
{
    PFQuery *query = [PFObject query];
    [query whereKey:@"" equalTo:@""];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        self.items = [NSArray arrayWithArray:objects];
        [self.tableView reloadData];
    }];
}

1) Set a NSTimer with 3600 intervalTime and trigger the fetch data function. 2) Just call [self.tableView reloadData] when the data has been fetch. It is all depends on how you design your coding structure.