【发布时间】:2014-03-31 03:18:58
【问题描述】:
我正在尝试为我的应用程序实现“刷新”按钮。该应用程序解析 Json 文件并将数据放入表视图中。我想制作一个按钮,当按下它时它会尝试连接到服务器并获取更新的数据。 到目前为止我做了什么:
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
self.navigationItem.rightBarButtonItem = button;
我有一个方法叫做刷新:
-(void) refresh{
[self.tableView reloadData];
}
但它似乎根本不起作用。
我获取Json数据的方式是这样的:
#import "JSONLoader.h"
#import "Location.h"
#import "Reachability.h"
@implementation JSONLoader
- (NSArray *)locationsFromJSONFile:(NSURL *)url {
// Create a NSURLRequest with the given URL
NSError *requestError = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
// Get the data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
// Now create a NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Create a new array to hold the locations
NSMutableArray *locations = [[NSMutableArray alloc] init];
// Get an array of dictionaries with the key "locations"
NSArray *array = [jsonDictionary objectForKey:@"locations"];
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
// Create a new Location object for each one and initialise it with information in the dictionary
Location *location = [[Location alloc] initWithJSONDictionary:dict];
// Add the Location object to the array
[locations addObject:location];
}
// Return the array of Location objects
return locations;
}
@end
如何使刷新按钮起作用?
【问题讨论】:
-
你在哪里调用你的刷新函数?
-
你的数据中是否包含数据??
-
是的,它包含数据并且按预期工作。问题是当用户在没有互联网连接的情况下打开应用程序时,不会获取数据。当互联网处于活动状态时,它可以正常工作。我要做的是让刷新按钮重新连接并在用户再次上网时获取数据。
-
您想检查是否在互联网开启或点击按钮时自动更新您的表格视图想要重新加载?