NSOperationQueue
is the recommended way to perform multi-threaded tasks to avoid blocking the main thread. Background thread is used for tasks that you want to perform while your application is inactive, like GPS indications or Audio streaming.
If your application is running in foreground, you don't need background thread at all.
For simple tasks, you can add a operation to a queue using a block:
NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
// Perform long-running tasks without blocking main thread
}];
More info about NSOperationQueue and how to use it.
The upload process will continue while in background, but your application will be eligible to be suspended, and thus the upload may cancel. To avoid it, you can add the following code to application delegate to tell the OS when the App is ready to be suspended:
- (void)applicationWillResignActive:(UIApplication *)application {
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Wait until the pending operations finish
[operationQueue waitUntilAllOperationsAreFinished];
[application endBackgroundTask: bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…