【发布时间】:2013-12-16 15:48:46
【问题描述】:
我目前正在开发一款应用程序,供参加大型年度会议的协会成员使用。
应用程序将从应用程序创建的数据库中提取数据并通过网络服务填充它。 Web 服务分为 8 页(这可能会增加)。每个页面代表数据库中的一个表。该应用程序将具有多个表视图,这些视图将由数据库中一个或多个表中的数据填充。
我需要的是浏览表列表、连接到它们各自的 Web 服务页面然后填充各自的数据库表的最佳方法。此更新需要在后台进行,这样 UI 才不会变得无响应和/或显示下载/更新/等待状态。
到目前为止,我有一个表名的静态数组,并有一个循环遍历该数组并附加一个带有名称的 URL 字符串,例如:
-(void)startUpdate
{
NSArray* tableNames = @[@"speaker", @"exhibitor", @"workshop", @"workshopspeakers", @"schedule", @"location", @"feedback", @"note", @"usage", @"user"];
NSUInteger loopCount = tableNames.count;
for (int i = 0; i < loopCount; ++i){
NSString *tableName = [tableNames objectAtIndex:i];
[self fetchObjectsWithTableName:[tableName mutableCopy] completion:^(NSArray* objects, NSError*error){
if (error) {
} else {
}
}];
}
}
fetchObjectsWithTableName 方法然后具有连接并检索数据:
-(void)fetchData:(NSString *)tableName
withCompletion:(completion_t)completionHandler
{
NSString *currentURL = [NSString stringWithFormat:@"https://testapi.someURL.com/api/congress/%@", tableName];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:currentURL]];
[request addValue:@"application/json" forHTTPHeaderField:(@"Accept")];
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError* err = error;
NSArray* objects; // final result array as a representation of JSON Array
if (response) {
NSHTTPURLResponse *newResp = (NSHTTPURLResponse*)response;
if (newResp.statusCode == 200) {
NSLog(@"FetchData - Status code = %li", (long)newResp.statusCode);
if ([data length] >0 && error == nil)
{
NSError* localError;
objects = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (objects) {
if (completionHandler) {
completionHandler(objects, nil);
}
//NSLog(@"Objects in current table - %@ = %@", tableName, objects);
[self.tables addObject:objects];
// NSLog(@"Tables now = %@", self.tables);
NSLog(@"FetchData - Objects in current table - %@ = %lu", tableName, (unsigned long)objects.count);
return;
} else {
err = localError;
}
} else {
NSLog(@"FetchData - objects is empty");
return;
// err = ...
}
}
NSLog(@"FetchData - Response code not 200@");
}
if (objects == nil) {
NSLog(@"FetchData - Nothing found in table: %@", tableName);
//assert(err);
if (completionHandler) {
completionHandler(nil, err);
}
}
}];
}
目前这会遍历表名数组,根据每个表名建立连接,然后拉回 JSON 数据并将其存储在临时数组“对象”中。我想我现在需要的是,在这个“对象”数组的每次迭代中,都被复制到数据库中的相关表中,即“扬声器”表名建立连接:https://testapi.someURL.com/api/congress/speaker 并且 JSON 被输入到数据库中表“扬声器”。我如何以及在哪里这样做?我需要向 startUpdate 添加完成处理程序吗?如果是这样,怎么做?尽管查看了几个示例,但我不了解完成处理程序。谢谢。
【问题讨论】:
标签: ios objective-c cocoa-touch sqlite