Iam с трудом обновляет мой планшет с новыми результатами, когда пользователь переходит к обновлению (UIRefreshControl). Контроллер работает правильно, но данные никогда не обновляются. Я попытался стереть переменную raw-data, и мой NSArray, который содержит все данные, но, похоже, не работает. Я новичок в программировании на iPhone, так что простите меня, это глупый вопрос.Правильно обновить данные JSON в табличном виде
Если мне удастся его исправить, было бы неправильно удалить все данные, которые я уже вытащил? Есть простой способ добавить изменения, учитывая, что большинство моих пользователей будут использовать соединения 3G/Edge. Вот мой класс реализации для TableViewController:
#import "Nyhetsfane.h"
@interface Nyhetsfane()
@end
@implementation Nyhetsfane
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Kaller på slide to update.
[self updateTable];
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:@selector(updateTable) forControlEvents:UIControlEventValueChanged];
[refreshControl setAttributedTitle:[[NSAttributedString alloc] initWithString:@"Dra for å oppdatere"]];
self.refreshControl = refreshControl;
}
- (void)updateTable{
// Viser "spinner" for å symbolisere nettverkstrafikk.
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// URL til JSON filen
NSURL *newsUrl = [NSURL URLWithString:@"http://localhost:7192/fadderapp/events.json"];
//URL Requestobjekt for å kontrollere tilkobling
NSURLRequest *newsRequest = [NSURLRequest requestWithURL:newsUrl];
[[NSURLConnection alloc]initWithRequest:newsRequest delegate:self];
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[newsRawData setLength:0];
newsRawData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[newsRawData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
newsCases = [NSJSONSerialization JSONObjectWithData:newsRawData options:0 error:0];
[self.tableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Feil" message:@"Det har oppstått en feil ved nedlastingen av data. Dobbeltsjekk at du er koblet til internett" delegate:nil cancelButtonTitle:@"Fortsett" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [newsCases count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
cell.textLabel.text = [[newsCases objectAtIndex:indexPath.row]objectForKey:@"navn"];
return cell;
}
...
Для всех это стоит, вот мой JSON корм:
[
{"navn": "Registration", "tidspunkt": "Monday 15:05", "beskrivelse": "Demo!"},
{"navn": "Party!", "tidspunkt": "Monday 19:30", "beskrivelse": "Demo"}
]
инициализирует ваши newCases – Hiren
вы уверены, что после того, как обновление данных, который возвращается, имеет различные значения, чем старый? –
Вы подтвердили, что вызывается 'updateTable'? Вызывается 'connectionDidFinishLoading'? Имеются ли в "newsCases" правильные данные? –