Refreshing and Maintaining Your App Using Background Tasks
At a glance
| Item | Summary |
|---|---|
| Purpose | Use scheduled background tasks for refreshing your app content and for performing maintenance. |
| App architecture | A Swift sample with the source-visible chain AppDelegate → FeedTableViewController → ColorTransformer → BackgroundTasks APIs. |
| Main patterns | View-controller organization, Protocol-oriented abstraction, Delegate or data-source callbacks |
| Project style | 8 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries. |
| Execution model | Source-visible boundaries: DispatchQueue.main.async, DispatchQueue(label:); none alone proves a background thread. |
| State/event model | No structured observation or publisher-scheduling marker indexed. |
| Key frameworks/packages | CoreData, Foundation, UIKit, BackgroundTasks; these are source dependencies, not architecture labels. |
Project structure
Source bundle/
├── ColorFeed/
│ ├── Operations.swift
│ ├── AppDelegate.swift
│ ├── ColorView.swift
│ ├── FeedTableViewController.swift
│ ├── Server.swift
│ ├── Mocks.swift
│ ├── PersistentContainer.swift
│ ├── FeedEntryTableViewCell.swift
│ └── Base.lproj/
│ ├── LaunchScreen.storyboard
│ └── Main.storyboard
└── ColorFeed.xcodeproj/
├── .xcodesamplecode.plist
└── project.pbxproj
Structure observations
- Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
- Primary languages: Swift.
- The verified tree contains 7 project/configuration file(s) and 21 source declaration(s).
Overall architecture
flowchart LR
N1["AppDelegate"]
N2["FeedTableViewController"]
N3["ColorTransformer"]
N4["BackgroundTasks APIs"]
N1 --> N2
N2 --> N3
N3 --> N4
Reference code
ColorFeed/AppDelegate.swift:11 — architecture anchor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// ...
var window: UIWindow?
// ...
}Interpretation
The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into Background Tasks.
Ownership and state
classDiagram
FetchMostRecentEntryOperation o-- NSManagedObjectContext : context
FetchMostRecentEntryOperation o-- FeedEntry : result
DownloadEntriesFromServerOperation o-- NSManagedObjectContext : context
DownloadEntriesFromServerOperation o-- Server : server
Ownership evidence
ColorFeed/Operations.swift:48 — stored dependency or nearest verified ownership anchor
class FetchMostRecentEntryOperation: Operation {
private let context: NSManagedObjectContext
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
FetchMostRecentEntryOperation |
NSManagedObjectContext (context) |
stores or receives | Initialized by the owner; the binding is immutable |
FetchMostRecentEntryOperation |
FeedEntry (result) |
stores or receives | App/module collaborators |
DownloadEntriesFromServerOperation |
NSManagedObjectContext (context) |
stores or receives | Initialized by the owner; the binding is immutable |
DownloadEntriesFromServerOperation |
Server (server) |
stores or receives | Initialized by the owner; the binding is immutable |
Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Queue scheduling | DispatchQueue.main.async |
The source addresses the main dispatch queue. | ColorFeed/ColorView.swift:44 |
| Queue scheduling | DispatchQueue(label:) |
The source constructs a dispatch queue; its label alone does not prove a thread. | ColorFeed/Mocks.swift:13 |
@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.
Reference code
ColorFeed/ColorView.swift:44 — representative execution boundary
DispatchQueue.main.async() {
guard !operation.isCancelled else { return }
self.setImage(image: image, animated: true)
}State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| Source import | CoreData |
The cited file imports this module; runtime use and architectural role are not inferred. | ColorFeed/FeedTableViewController.swift:9 |
| Source import | Foundation |
The cited file imports this module; runtime use and architectural role are not inferred. | ColorFeed/Mocks.swift:8 |
| Source import | UIKit |
The cited file imports this module; runtime use and architectural role are not inferred. | ColorFeed/AppDelegate.swift:8 |
| Source import | BackgroundTasks |
The cited file imports this module; runtime use and architectural role are not inferred. | ColorFeed/AppDelegate.swift:9 |
receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.
Class and protocol design
ColorFeed/Server.swift:10 — representative type boundary
protocol Server {
// Fetch any entries on the server that are more recent than the start date.
@discardableResult
func fetchEntries(since startDate: Date, completion: @escaping (Result<[ServerEntry], Error>) -> Void) -> DownloadTask
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
AppDelegate |
Receives callback-driven events | UIResponder, UIApplicationDelegate |
FetchMostRecentEntryOperation |
Encapsulates one executable operation | Operation |
DownloadEntriesFromServerOperation |
Encapsulates one executable operation | Operation |
AddEntriesToStoreOperation |
Encapsulates one executable operation | Operation |
DeleteFeedEntriesOperation |
Encapsulates one executable operation | Operation |
ColorView |
User-interface presentation and input forwarding | UIView |
FeedTableViewController |
View lifecycle, callbacks, and feature coordination | UITableViewController, NSFetchedResultsControllerDelegate |
ColorTransformer |
Transforms feature data or representations | NSSecureUnarchiveFromDataTransformer |
Server |
Defines a capability or collaboration contract | Concrete collaborators/imported frameworks |
DownloadTask |
Defines a capability or collaboration contract | Concrete collaborators/imported frameworks |
The source explicitly defines local protocol relationships: MockServer → Server, MockDownloadTask → DownloadTask.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
server (ColorFeed/AppDelegate.swift:16) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
updateContents (ColorFeed/ColorView.swift:26) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: hide an implementation step that is not part of the collaboration surface. |
imageView (ColorFeed/ColorView.swift:54) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
queue (ColorFeed/ColorView.swift:55) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
Reference code
ColorFeed/AppDelegate.swift:16 — representative boundary
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// ...
private let server: Server = MockServer()
// ...
}Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| View lifecycle, callbacks, and feature coordination | FeedTableViewController |
The source’s Controller suffix makes this role explicit. |
| Receives callback-driven events | AppDelegate |
The source’s Delegate suffix makes this role explicit. |
| Encapsulates one executable operation | AddEntriesToStoreOperation, DeleteFeedEntriesOperation, DownloadEntriesFromServerOperation, FetchMostRecentEntryOperation |
The source’s Operation suffix makes this role explicit. |
| Transforms feature data or representations | ColorTransformer |
The source’s Transformer suffix makes this role explicit. |
| User-interface presentation and input forwarding | ColorView |
The source’s View suffix makes this role explicit. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | ColorFeed/FeedTableViewController.swift:11 |
A controller is the verified coordination boundary; this is MVC-style only where a separate model is present. |
| Protocol-oriented abstraction | ColorFeed/Mocks.swift:12 |
A local protocol and concrete conformance create an explicit capability boundary. |
| Delegate or data-source callbacks | ColorFeed/AppDelegate.swift:12 |
Callback protocols invert event delivery back into the sample’s owner. |
Main application flow
One app-refresh launch reschedules the next request, constructs an ordered operation chain, wires cancellation and completion callbacks, and returns success to the system task.
sequenceDiagram
participant Scheduler as BGTaskScheduler
participant App as AppDelegate
participant Factory as Operations
participant Queue as OperationQueue
participant Last as Last operation
participant Task as BGAppRefreshTask
Scheduler-->>App: Registered launch handler
App->>Scheduler: scheduleAppRefresh()
App->>Factory: getOperationsToFetchLatestEntries(...)
Factory-->>App: Ordered operations
App->>Task: Set expirationHandler
App->>Last: Set completionBlock
App->>Queue: addOperations(waitUntilFinished: false)
Queue-->>Last: Complete or cancel chain
Last-->>Task: setTaskCompleted(success)
Reference code
ColorFeed/AppDelegate.swift:79 — handleAppRefresh
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleAppRefresh()
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let context = PersistentContainer.shared.newBackgroundContext()
let operations = Operations.getOperationsToFetchLatestEntries(using: context, server: server)
let lastOperation = operations.last!
task.expirationHandler = {
// After all operations are cancelled, the completion block below is called to set the task to complete.
queue.cancelAllOperations()
}
lastOperation.completionBlock = {
task.setTaskCompleted(success: !lastOperation.isCancelled)
}
queue.addOperations(operations, waitUntilFinished: false)
}Naming conventions
- Types: Controller: FeedTableViewController; Delegate: AppDelegate; Operation: AddEntriesToStoreOperation, DeleteFeedEntriesOperation, DownloadEntriesFromServerOperation, FetchMostRecentEntryOperation; Transformer: ColorTransformer; View: ColorView.
- Protocols:
Server,DownloadTask. - Methods:
getOperationsToFetchLatestEntries,main,cancel,finish,start,application,applicationDidEnterBackground,scheduleAppRefresh. - Files:
ColorFeed/Operations.swift,ColorFeed/AppDelegate.swift,ColorFeed/ColorView.swift,ColorFeed/FeedTableViewController.swift,ColorFeed/Server.swift,ColorFeed/PersistentContainer.swift.
Architecture takeaways
AppDelegateis the main source-visible entry or composition anchor for this sample.- Framework work reaches CoreData, UIKit, BackgroundTasks through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
- Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
- Access-control conclusions separate verified language visibility from the likely design rationale.
- Local protocol relationships provide an explicit substitution boundary.
Source map
| Source file | Relevant symbols |
|---|---|
ColorFeed/AppDelegate.swift |
Cited implementation, UIKit, BackgroundTasks, AppDelegate |
ColorFeed/Operations.swift |
Cited implementation, Operations, FetchMostRecentEntryOperation, DownloadEntriesFromServerOperation, OperationError, AddEntriesToStoreOperation, DeleteFeedEntriesOperation |
ColorFeed/Server.swift |
Server, DownloadTask, ServerEntry, Color |
ColorFeed/ColorView.swift |
Cited implementation, DispatchQueue.main.async, ColorView, Parameters |
ColorFeed/FeedTableViewController.swift |
FeedTableViewController, CoreData |
ColorFeed/Mocks.swift |
Cited implementation, DispatchQueue(label:), Foundation, MockServer, DownloadError, MockDownloadTask |
ColorFeed/PersistentContainer.swift |
PersistentContainer, Color, ColorTransformer |
ColorFeed/FeedEntryTableViewCell.swift |
FeedEntryTableViewCell |