多くのコードと、これを行うためのめまいがするほどの方法を調べた後、「単純な」例を見つけることができませんでした。ネット上の多くの例は、ARC以前のものであるか、私の理解レベルには複雑すぎます。さらに他の例は、もはや開発中ではないサードパーティのライブラリに依存していました。より最新のさらに別の例では、30 秒のタイムアウトがあり、すべてを完了する必要があります (ios7 fetch)。これは、ビジー状態の 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);
}