【发布时间】:2017-05-31 11:20:06
【问题描述】:
我是 iOS 新手,一直在尝试在 UITableView 中加载 JSON 数据(在 UIViewController 中,在标签栏控制器中)。 JSON 数据很大,我也尝试过使用AFNetworking 库。但数据仍然需要超过 15 秒。加载。
这是我尝试过的: 方法#2
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self saveData];
return YES;
}
-(void) saveData
{
NSString * userType= @"3" ;
NSString * userID= @"33" ;
NSString * URLString = [NSString stringWithFormat:@"http://<some_url>/%@/%@/",userType,userID];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer =[AFHTTPResponseSerializer serializer];
[manager GET:leadsURLString parameters:nil progress:nil success:^(NSURLSessionTask *task, NSData* responseObject) {
NSError * error = nil;
NSArray * lData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Leads:%@",lData);
if (error != nil) {
NSLog(@"JSON Error: %@", [error localizedDescription]);
}
// Write the file .
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docDirectory = [paths objectAtIndex:0];
NSString * lFilePath = [NSString stringWithFormat:@"%@",[docDirectory stringByAppendingPathComponent:@"leads"]]; // File
if (![leadsData writeToFile:lFilePath atomically:YES]) {
NSLog(@"Couldn't save leads data.");
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
@end
Code for tableView
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docDirectory = [paths objectAtIndex:0];
NSString * projFilePath = [NSString stringWithFormat:@"%@",[docDirectory stringByAppendingPathComponent:@"leads"]]; // file
if ([[NSFileManager defaultManager] fileExistsAtPath:projFilePath])
{
_projects = [[NSMutableArray alloc] initWithContentsOfFile:projFilePath];
}
else
{
_projects = [NSMutableArray arrayWithObject:[NSDictionary dictionaryWithObject:@"No Project" forKey:@"project_name"]];
}
[self.tableView reloadData];
}
最初尝试在视图控制器加载时加载数据,耗时太长。
然后尝试在 Appdelegate 中加载数据并保存,并在视图控制器加载时加载,仍然花费了足够长的时间。
尝试在 Appdelegate 中加载数据,然后在各自的视图控制器中进行设置,但无法实现。
谁能提出最好的方法来完成它?
【问题讨论】:
-
添加尝试过的代码。
-
添加了尝试过的代码。
-
如果获取数据需要很长时间,可能是网速或服务器问题。你不能做任何事情!一旦你得到回应,你应该重新加载你的表格视图,就是这样!你这边就完成了!
-
我正在我的 viewControllers 中这样做,重新加载 tableView。正如您所说,这可能是一个问题,因为正在加载大约 6000 多条记录。但这对于 JSON 数据来说太过分了吗?
-
添加在tableview中显示的代码。
标签: ios objective-c json uitableview