Implementing pull to refresh in a UITableView
A table view often holds information that changes while it is open: departure times for a Sydney train, disruption alerts for a Melbourne tram route, or a new order in an Australian marketplace. The pull-to-refresh gesture turns a downward scroll into a deliberate request for the newest records, giving the user a physical cue and an immediate visual response while content reloads.
For an iOS developer working in UIKit, UIRefreshControl provides the native foundation for this interaction. This implementation connects the control to a UITableView, loads data asynchronously, preserves useful rows when a request fails, and finishes the loading state reliably. The same pattern suits message threads, notification feeds, and local listings viewed from Melbourne to Darwin.
How the refresh gesture works
UIKit recognises the downward drag when the scroll view is already at its top. As the user pulls, the system reveals a spinner, and releasing the gesture sends a .valueChanged event to the refresh control. The controller receives that event, starts the request, and decides when the indicator should disappear.
Treat the action as a replacement of the current first page rather than an append operation. A refresh should reload the newest records, reset any pagination token, and update existing rows in place where possible. This distinction prevents duplicates when the view also supports loading older items as the user scrolls toward the bottom.
Connecting UIRefreshControl to the table view
Keep a strong reference to the refresh control, assign it to the table view, and register its target during view setup. A minimal programmatic setup looks like this:
final class FeedViewController: UIViewController {
private let tableView = UITableView(frame: .zero)
private let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
tableView.refreshControl = refreshControl
refreshControl.addTarget(
self,
action: #selector(refreshTriggered),
for: .valueChanged
)
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
@objc private func refreshTriggered() {
// Start the data request here.
}
}
Register the target once rather than adding it repeatedly each time the view appears. If the interface uses a custom tint, set refreshControl.tintColor; otherwise, the system colour provides a familiar appearance. Adding UIRefreshControl does not change the table's data source, cell registration, or row-selection behaviour.
For programmatic refreshes, beginRefreshing() shows the indicator but does not send .valueChanged, so the same loading method must be called explicitly. Once new values arrive, assign them to the model that backs the data source and call tableView.reloadData(). A diffable data source can apply a snapshot instead, producing more targeted row updates and reducing visible jumps.
Loading fresh data with Swift concurrency
Replace the placeholder action with a task that calls the service. Keep retrieval in a service or repository rather than inside the view controller. The service should return the latest first page and throw a normal error for timeouts, invalid responses, and offline conditions. Because UITableView and UIRefreshControl are UIKit objects, update them on the main actor.
private let service: FeedService
private var items: [Item] = []
private var isLoading = false
@objc private func refreshTriggered() {
Task { [weak self] in
await self?.loadLatestData()
}
}
@MainActor
private func loadLatestData() async {
guard !isLoading else { return }
isLoading = true
defer {
isLoading = false
refreshControl.endRefreshing()
}
do {
let latest = try await service.fetchLatest()
guard !Task.isCancelled else { return }
items = latest
tableView.reloadData()
} catch is CancellationError {
// A newer request now owns the visible state.
} catch {
showRefreshError(error)
}
}
The defer block is important: the spinner must stop after success, failure, or cancellation. The isLoading guard prevents repeated pulls from creating duplicate requests. If the screen supports infinite scrolling, successful refreshes should also clear the next-page token so subsequent scrolling does not mix old pagination state with new records.
Store and transmit timestamps in UTC, then render them in the user's local zone. Australia makes that distinction worth testing because Perth, Adelaide, Brisbane, and Sydney use different time zones. The same care applies to Australian commerce data: show prices in Australian dollars and remember that consumer App Store prices already include the country's 10% GST.
Handling errors, empty data, and retries
A failed request should not automatically erase the screen. Connectivity can be unreliable beyond Australia's metropolitan centres, and a cached departure board or saved message thread is often more useful than an empty view. Keep the current rows visible, end the refresh animation, and explain the problem with a compact error message or inline retry control.
Separate “no results” from “could not load.” An empty search may be a valid state with guidance about changing filters, while a network failure should offer a retry action. Both states need accessible labels, and the retry control should meet the platform's minimum touch target. Announcing a successful update through VoiceOver is helpful when it changes content the user was waiting for.
Do not present every failure as a fatal error. Timeouts and brief connection loss are expected operating conditions, so log diagnostic details privately and show the user a recoverable message. Australian interfaces can use familiar language such as “arvo” and “no worries” where the brand voice allows it, rather than adopting stiff corporate phrasing.
Protecting context and accessibility
The native refresh control is preferable to a custom pan gesture because it already communicates availability, progress, and completion through familiar platform behaviour. It also gives VoiceOver users an accessible action. Keep visible labels descriptive—for example, “Refresh train departures”—and verify the interaction with VoiceOver, Dynamic Type, and Reduce Motion enabled.
A reload can move the user's position when row heights or content counts change. Capture a visible row before applying the update, then restore its location if the content set causes a jump. Diffable snapshots help with this, but they do not replace deliberate scroll-position handling in every layout.
Separation of responsibilities also keeps the feature maintainable: the view controller coordinates the interaction, while the service owns network work and decoding. Developers who maintain larger tools can see a similar boundary in a custom NetBeans module, where one capability is packaged behind a defined interface instead of being tangled with the host application.
Practical recommendations for reliable refreshes
Three practical approaches suit different iOS codebases, so choose according to the screen's purpose rather than adding several competing refresh mechanisms.
| Approach | Best fit | Advantage | Trade-off |
|---|---|---|---|
UIRefreshControl |
UIKit data screens | Native gesture and indicator | Requires explicit loading and failure handling |
SwiftUI .refreshable |
SwiftUI lists | Concise, state-driven API | Uses a different view lifecycle |
| Navigation-bar refresh item | Infrequent or critical updates | Visible and easy to invoke | Consumes fixed screen space |
For a production implementation, the following recommendations keep the interaction predictable:
- Keep network and decoding work in a service, with UI updates isolated to the main actor.
- End the refresh indicator on every exit path, including cancellation and failure.
- Preserve cached rows when the network is unavailable and give the user a retry route.
- Reset pagination state after replacing the first page to avoid duplicate rows.
- Test VoiceOver, Dynamic Type, Reduce Motion, and large text with realistic row content.
- Store dates in UTC and localise prices and times for Australian users.
- Cover slow, empty, failed, cancelled, and repeated requests with unit and UI tests.
A slow mock service and a forced failure exercise both branches without relying on live infrastructure. They also reveal whether the spinner, cached content, and retry controls behave correctly under realistic timing.
Turning the pattern into your own app
Pull to refresh looks like a small piece of UI, but its reliability comes from coordination: a clear gesture, isolated data loading, correct state transitions, and content that remains understandable when the network misbehaves. Keeping those responsibilities separate makes the feature easier to test and reuse across screens.
My next concrete step is to implement UIRefreshControl in the sample feed with cached mock rows and a deliberately slow mock service.