在查看了大量代码和令人眼花缭乱的方法之后,我真的找不到一个“简单”的例子。网上的很多例子都是 ARC 之前的,或者对我的理解水平来说太复杂了。还有其他示例取决于不再开发的 3rd 方库。还有一些最新的例子有 30 秒的超时,在这个时间内必须完成所有操作(ios7 获取),这似乎不足以在繁忙的 Wi-Fi 网络上快速下载。最终,我确实设法拼凑出一个工作示例,该示例确实每 20 秒运行一次后台下载。还不知道如何更新 UI。
AppDelegate.m
#import "bgtask.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
bgtask *b = [[bgtask alloc] initTaskWithURL:@"http://www.google.com" app:application];
return YES;
}
bgtask.h
#import <Foundation/Foundation.h>
@interface bgtask : NSOperation
@property (strong, atomic) NSMutableData *webData;
@property (strong, atomic) UIApplication *myApplication;
- (id) initTaskWithURL:(NSString *)url app:(UIApplication *)application;
@end
bgtask.m
#import "bgtask.h"
@implementation bgtask
UIBackgroundTaskIdentifier backgroundTask;
@synthesize webData = _webData;
@synthesize myApplication = _myApplication;
NSString *mURL;
// connect to webserver and send values. return response data
- (void) webConnect
{
NSURL *myURL = [NSURL URLWithString:mURL];
_webData = [NSData dataWithContentsOfURL:myURL];
if (_webData)
{
// save response data if connected ok
NSLog(@"connetion ok got %ul bytes", [_webData length]);
}
else
{
NSLog(@"connection failed");
//TODO: some error handling
}
}
- (void) timerTask:(NSTimer *) timer
{
backgroundTask = [_myApplication beginBackgroundTaskWithExpirationHandler:
^{
dispatch_async(dispatch_get_main_queue(),
^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[_myApplication endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
NSLog (@"Running refresh...");
[self webConnect];
dispatch_async(dispatch_get_main_queue(),
^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[_myApplication endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
});
}
- (id) initTaskWithURL:(NSString *)url app:(UIApplication *)application
{
self = [super init];
if (self)
{
// setup repeating refresh task.
// Save url, application for later use
mURL = [[NSString alloc] initWithString:url];
_myApplication = application;
[NSTimer scheduledTimerWithTimeInterval:20.0
target:self
selector:@selector(timerTask:)
userInfo:nil
repeats:YES];
NSLog (@"task init");
}// if self
return (self);
}