AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : NSObject {
// Instance member of our background task process
UIBackgroundTaskIdentifier bgTask;
}
@end
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Application entered background state.");
// bgTask is instance variable
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}];
dispatch_async(dispatch_get_main_queue(), ^{
if ([application backgroundTimeRemaining] > 1.0) {
// Start background service synchronously
[[BackgroundCleanupService getInstance] run];
}
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}
在上面的实现中有几个关键行:
第一行是 bgTask = [application beginBackgroundTaskWithExpirationHandler...,它要求额外的时间在后台运行清理任务。
第二个是以dispatch_async开头的委托方法的最后一个代码块。它基本上是通过调用[application backgroundTimeRemaining] 检查是否还有时间运行操作。在此示例中,我希望运行一次后台服务,但您也可以在每次迭代时对 backgroundTimeRemaining 使用循环检查。
[[BackgroundCleanupService getInstance] run] 行将调用我们现在将构建的单例服务类。
随着应用程序委托准备好触发我们的后台任务,我们现在需要一个与 Web 服务器通信的服务类。在以下示例中,我将发布一个虚构的会话密钥并解析 JSON 编码的响应。此外,我正在使用两个有用的库来发出请求并反序列化返回的 JSON,特别是 JSONKit 和 ASIHttpRequest。
BackgroundCleanupService.h
#import <Foundation/Foundation.h>
@interface BackgroundCleanupService : NSObject
+ (BackgroundCleanupService *)getInstance;
- (void)run;
@end
BackgroundCleanupService.m
#import "BackgroundCleanupService.h"
#import "JSONKit.h"
#import "ASIHTTPRequest.h"
@implementation BackgroundCleanupService
/*
* The singleton instance. To get an instance, use
* the getInstance function.
*/
static BackgroundCleanupService *instance = NULL;
/**
* Singleton instance.
*/
+(BackgroundCleanupService *)getInstance {
@synchronized(self) {
if (instance == NULL) {
instance = [[self alloc] init];
}
}
return instance;
}
- (void)run {
NSURL* URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/user/%@/endsession", @"SESSIONKEY"]];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:URL];
[request setTimeOutSeconds:20]; // 20 second timeout
// Handle request response
[request setCompletionBlock:^{
NSDictionary *responseDictionary = [[request responseData] objectFromJSONData];
// Assume service succeeded if JSON key "success" returned
if([responseDictionary objectForKey:@"success"]) {
NSLog(@"Session ended");
}
else {
NSLog(@"Error ending session");
}
}];
// Handle request failure
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"Service error: %@", error.localizedDescription);
}];
// Start the request synchronously since the background service
// is already running on a background thread
[request startSynchronous];
}
@end
可能会有所帮助