大家好,小弟最近想自己试着使用NSURLSession来写写看如何抓到JSON的资料
主要架构就是用一个TableViewControler把抓回来的JSON资料一笔一笔显示出来
上网查了许多资料自己试做后,有成功抓到JSON资料,
但是目前遇到问题是资料回来之前,
TableViewController 就已经建立好了,
所以一开APP不会显示资料,我需要等资料回来后,
准备一个执行[TableView reloadData]的方法的按钮,
按下后才能在TableView上显示资料。
我参照网络上以及Apple的一些官方sample,
把抓资料的NSURLSession写在AppDelegate的Class里
可能应为对于能在哪个时机点让APP自动执行reloadData还不是很了解,
想请教各位大大,感恩!
程式码如下(目前的写法曾经有几次成功在APP执行后自动显示,但成功机率很低..):
static NSString * const taipeiUrl = @"http://data.taipei.gov.tw/opendata/apply/json/RkRDNjk0QzUtNzdGRC00ODFCLUJBNDktNEJCMUVCMDc3ODFE";
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:taipeiUrl] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSLog(@"error = %@", [error description]);
if (error != nil)
{
[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
{
abort();
}
else
{
[self handleError:error];
}
}];
}
else{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
self.newsArray = [json valueForKey:@"name"];
NSLog(@"%@", self.newsArray);
__weak AppDelegate *weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^(void){
NewsTableViewController *rootViewController = (NewsTableViewController *)[(UINavigationController *)weakSelf.window.rootViewController topViewController];
[rootViewController.tableView reloadData];
});
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}];
[dataTask resume];
//UI
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//create the navigation controller and add the controllers view to the window
self.navigationController = [[UINavigationController alloc] init];
[self.window addSubview:[self.navigationController view]];
NewsTableViewController *newsViewController = [[NewsTableViewController alloc] initWithNibName:@"NewsTableViewController" bundle:nil];
//push the first viewcontroller into the navigation view controller stack
[self.navigationController pushViewController:newsViewController animated:YES];
self.window.backgroundColor = [UIColor whiteColor];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
return YES;
}
// handleError:error
// Reports any error with an alert which was received from connection or loading failures.
- (void)handleError:(NSError *)error
{
NSString *errorMessage = [error localizedDescription];
// alert user that our current record was deleted, and then we leave this view controller
//
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Cannot Show Top Paid Apps"
message:errorMessage
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
// dissmissal of alert completed
}];
[alert addAction:OKAction];
[self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}