gpt4 book ai didi

ios - 当从调度队列中的服务器检索数据时,如何处理应用程序进入后台?

转载 作者:行者123 更新时间:2023-11-29 03:17:38 25 4
gpt4 key购买 nike

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

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
});

});

即使应用程序进入后台,我如何从服务器检索数据?

感谢和问候苏门答腊

最佳答案

如果您的项目范围仅限于 iOS 7,那么您可以使用 iOS 7 及更高版本中提供的新后台模式。您可以在后台模式下获取数据,而无需任何额外的编码工作。

Background fetch

  [[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);
}
}

现在在你的 Controller 中。就这样吧

- (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);
}

注意:-如果您必须在 iOS 6 及更低版本上提供支持,请避免使用此方法。因为它不可用。

关于ios - 当从调度队列中的服务器检索数据时,如何处理应用程序进入后台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21501134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com