0

当应用程序每秒处于挂起/后台模式时,如何读取/更新本地 sqlite 数据?下面是我现在正在尝试做的代码我只想在每秒之后 NsLog 本地 Sqlite 表中存在的所有 Id 但无法做到这一点。谁能告诉我我做错了什么,或者任何人都可以纠正以下代码。 提前致谢

-(void)applicationDidEnterBackground:(UIApplication *)app
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
        if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
            UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance

            __block UIBackgroundTaskIdentifier background_task; //Create a task object

            background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
                [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                background_task = UIBackgroundTaskInvalid; //Set the task to be invalid

                //System will be shutting down the app at any point in time now
            }];

            //Background tasks require you to use asyncrous tasks

            dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue);
            dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), 1*NSEC_PER_SEC, 0*NSEC_PER_SEC);
            dispatch_source_set_event_handler(timerSource, ^{
                [self BackGroundTaskFunction];
            });
            dispatch_resume(timerSource);
        }
    }
}
-(void)BackGroundTaskFunction
{
   [self GetUserName]
    if (recordArray.count>0) 
    {
        for (int i=0; i<recordArray.count; i++) 
        {
            DB_data *db=(DB_data *)[recordArray objectAtIndex:i];
            Nslog(@"%d",db.Id);          
        }
    }
}
-(void)GetUserName{
    self.recordArray = [[NSMutableArray alloc] init];
    {
        const char *sql = "select * from UserName";
        sqlite3_stmt *selectStatement;

        int returnValue = sqlite3_prepare_v2(database, sql, -1, &selectStatement, NULL);
        if(returnValue == SQLITE_OK)
        {
            while(sqlite3_step(selectStatement) == SQLITE_ROW)
            {
                [recordArray addObject:[[DB_data alloc] initwithDataSet:sqlite3_column_int(selectStatement, 0) UserName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 1)]]];
            }
        }
        else
        {
            printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(database) );
        }

    }

}
4

2 回答 2

0

不,您不能这样做,只有播放音频、跟踪用户位置或 voip 客户端的应用程序才允许在后台运行。

如果您不属于这些类型的应用程序之一,那么您将无法在后台运行。

您发布的代码允许您运行最长 10 分钟的冗长过程。

于 2012-07-11T07:59:02.383 回答
0

我通过使用 NSRUNLOOP 解决了我的问题,它帮助我让应用程序继续在后台运行

于 2012-07-19T08:22:39.110 回答