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. |
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 {
// ...
}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
private let context: NSManagedObjectContext
var result: FeedEntry?
init(context: NSManagedObjectContext) {
self.context = context
}| 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.
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 — the launch handler configures the queue and both lifecycle callbacks before starting work.
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 = {
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/Operations.swift |
Operations, FetchMostRecentEntryOperation, DownloadEntriesFromServerOperation, OperationError, AddEntriesToStoreOperation, DeleteFeedEntriesOperation |
ColorFeed/AppDelegate.swift |
AppDelegate |
ColorFeed/ColorView.swift |
ColorView, Parameters |
ColorFeed/FeedTableViewController.swift |
FeedTableViewController |
ColorFeed/Server.swift |
Server, DownloadTask, ServerEntry, Color |
ColorFeed/Mocks.swift |
MockServer, DownloadError, MockDownloadTask |
ColorFeed/PersistentContainer.swift |
PersistentContainer, Color, ColorTransformer |
ColorFeed/FeedEntryTableViewCell.swift |
FeedEntryTableViewCell |