Ios 从调度队列中的服务器检索数据时,如何处理应用程序转到后台?

Ios 从调度队列中的服务器检索数据时,如何处理应用程序转到后台?,ios,grand-central-dispatch,Ios,Grand Central Dispatch,我正在创建一个从服务器检索数据的应用程序,如下所示: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ [self retrievedatafromserver]; dispatch_async(dispatch_get_main_queue(), ^{ //UIUpdation, fetch the image/data from DB

我正在创建一个从服务器检索数据的应用程序,如下所示:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

    [self retrievedatafromserver];

    dispatch_async(dispatch_get_main_queue(), ^{

        //UIUpdation, fetch the image/data from DB  and update into your UI
    });

});
即使应用程序转到后台,如何从服务器检索数据

谢谢和问候
sumana

当您的应用程序进入后台模式时。您可以访问代码几秒钟。假设后台队列仍在执行,并且您输入了后台。然后,当应用程序进入前台时,您可能需要调用该方法。(获取bool变量并检查流程是否已完成,如果流程已完成,则无问题。如果未完成,则再次调用该方法。)


如果你想让应用程序在后台模式下运行,那么你需要在plist中请求后台运行模式。查看此链接仅供参考,了解这些功能我们可以激活后台运行模式,您可以根据自己的使用情况激活其中任何功能

如果您的项目范围仅在iOS 7中,则您可以使用iOS 7及以后版本中的新后台模式。您可以在后台模式下获取数据,而无需进行任何额外的编码

  [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

既然你的应用程序已经知道启动后台抓取,让我们告诉它该怎么做。方法
-(void)application:(UIApplication*)application performFetchWithCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler
将协助执行此操作。每次执行后台提取时都会调用此方法,并且应该包含在AppDelegate.m文件中。完整版本如下所示:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    UINavigationController *navigationController = (UINavigationController*)self.window.rootViewController;
    id topViewController = navigationController.topViewController;
    if ([topViewController isKindOfClass:[ViewController class]]) {
        [(ViewController*)topViewController insertNewObjectForFetchWithCompletionHandler:completionHandler];
    } else {
        NSLog(@"Not the right class %@.", [topViewController class]);
        completionHandler(UIBackgroundFetchResultFailed);
    }
}
现在在你的控制器里。你喜欢吗

- (void)insertNewObjectForFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"Update the tableview.");
    self.numberOfnewPosts = [self getRandomNumberBetween:0 to:4];
    NSLog(@"%d new fetched objects",self.numberOfnewPosts);
    for(int i = 0; i < self.numberOfnewPosts; i++){
        int addPost = [self getRandomNumberBetween:0 to:(int)([self.possibleTableData count]-1)];
        [self insertObject:[self.possibleTableData objectAtIndex:addPost]];
    }
    /*
     At the end of the fetch, invoke the completion handler.
     */
    completionHandler(UIBackgroundFetchResultNewData);
}
-(void)insertNewObjectForFetchWithCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler{
NSLog(@“更新表视图”);
self.numberOfnewPosts=[self-getRandomNumberBetween:0到:4];
NSLog(@“%d个新获取的对象”,self.numberOfnewPosts);
for(int i=0;i
注意:-如果您必须在iOS 6及以下版本上提供支持,请避免这种方法。因为它不可用。

供您参考,