SwiftUI feedback that works offline
How to build automatic retries, an offline queue and reconnect code in the VoteFirst Swift package.
Free for one project and 100 votes. Paid plans start with a 14 day trial, no card.
Retries
A read and a write each get up to three attempts, with a quarter of a second, then half a second, between them.
Every request is tried three times before you hear about it.
None of the three numbers is a setting. An app that needs others can retry the call itself.
These failures are retried: no connection, a dropped connection, a timeout, a short rate limit wait, any server error and an idempotency conflict. That last one means an earlier copy of the same write is still running.
A plain conflict, meaning the vote is already there, is not retried, because repeating it changes nothing. Other 4xx answers are not retried either, because asking again the same way gets the same answer.
If the server names a wait, that wins, up to two seconds. Past that the error is handed to you, because somebody is watching a spinner and a minute of silence is a hang. A request gives up after 30 seconds. Cancelling the task that made the call cancels the request and throws CancellationError, not a VoteFirstError, so a view that left the screen shows nothing about it.
The offline queue
A write made with no connection throws a network error and is queued. It stays in a file in application support, one file for each project.
A vote with no network is kept, so show it as voted.
It survives the app being killed and launched again.
What is queued is the method, the path, the body and the idempotency key it was first attempted with. Only a network failure queues. A write the server refused is not queued, because asking again would be refused again.
Even the voter is handled. Minting the voter is itself a request, so with no network it is the first thing to fail. The write is queued anyway and the voter is minted when the queue drains. So an app opened for the first time on a plane behaves like one that went offline mid session.
That is why the sample draws the button as voted when it catches a network error. The vote is not lost, it is waiting.
import SwiftUI
import VoteFirst
struct VoteButton: View {
let featureID: Int
@State private var voted = false
@State private var waiting = 0
@State private var note: String?
var body: some View {
VStack(alignment: .leading) {
Button(voted ? "Voted" : "Vote") { Task { await vote() } }
if waiting > 0 { Text("\(waiting) waiting for a connection").font(.footnote) }
if let note { Text(note).font(.footnote) }
}
.task { waiting = await VoteFirst.waiting }
}
@MainActor
private func vote() async {
note = nil
do {
voted = try await VoteFirst.upvote(featureID: featureID).hasVoted
} catch let error as VoteFirstError {
if case .network = error { voted = true } else { note = error.errorDescription }
} catch {}
waiting = await VoteFirst.waiting
}
}Sending it
The package screens send the queue when they appear and when someone pulls to refresh, and they show how many writes are waiting.
The built in screens send the queue. Your own screens must.
Nothing is retried in the background.
If you draw your own screens, call send yourself when your own reachability says the connection is back. It first mints or renews the voter, because the server stores a write's response against the voter as well as the key, then replays each write in the order it was made. It returns how many left the queue.
A write that succeeds leaves the queue. A write refused for a reason that will not change leaves it too, because keeping it would mean retrying it forever. A write that fails for a reason worth retrying stops the drain there, and everything behind it keeps its place.
import Network
import VoteFirst
final class Reconnect {
private let monitor = NWPathMonitor()
func start() {
monitor.pathUpdateHandler = { path in
guard path.status == .satisfied else { return }
Task { _ = await VoteFirst.send() }
}
monitor.start(queue: DispatchQueue(label: "reconnect"))
}
}Reading errors
Every call throws one type, VoteFirstError. When the server answered and said no, it carries a typed code, a message and a status.
Branch on the code, and show the sentence it came with.
Quote the request id in a support email. It is echoed in X-Request-Id.
A network error means the request never got an answer. An api error means the server answered. It carries a code, the raw code the server wrote and a message written for a person. It also carries the field a validation failure was about, the status, a request id and the wait it asked for. Two shortcuts, code and isRetryable, keep the common case out of a switch.
A few codes deserve their own words. voterBanned means the project has stopped this voter writing, and they can still read, vote and like. validationFailed names the field to mark. rateLimited carries a retryAfter. A vote that is already there and a copy of a write still running are settled by the package itself, so you need not handle them.
func message(for error: VoteFirstError) -> String {
switch error.code {
case .voterBanned:
return "You can still read and vote, but you cannot post."
case .validationFailed:
return error.failure?.message ?? "Check the form."
case .rateLimited:
return "Busy right now. Try again in a minute."
default:
return error.errorDescription ?? "Something went wrong."
}
}Project limits
Your project gets 3,000 reads, 600 writes and 300 new voters a minute, with bursts of 300, 60 and 30.
The limits belong to your project, not to one phone.
Every copy of your app draws from the same bucket.
That makes the burst the number to design against, and the one to watch is new voters. Thirty one people opening your app for the first time in the same second is over the burst. Going over does not refuse one request. It turns that budget off for your whole project for sixty seconds, and every request against it answers rateLimited with a Retry-After of 60.
That wait is longer than the package will sleep through, so it arrives as an error for you to handle. Show a plain message and let the person try again later.
Try it
Turn on airplane mode, vote, and watch the waiting line appear. Turn it off and check that the count goes back to zero.
Test it with airplane mode on a real device.
Kill the app while it is waiting, then reopen it.
The queue is a file, so a vote made offline must still be there after a relaunch. If the line stays at one after the connection returns, the drain stopped on a write that failed for a retryable reason, and the next call to send will try it again.
Also try the first launch with no network at all. The write is queued without a voter, and the voter is minted when the queue drains.
What you get without writing it
No lost votes
A vote made offline waits in a file and survives a relaunch.
Safe repeats
Each write carries a key, so a retry cannot count a vote twice.
One error type
A typed code, a readable message and a request id for support.
Offline feedback screen in four steps
Most of the work is already in the package.
Treat a network error as queued
Draw the vote as made when the error is a network error.
Show what is waiting
Read VoteFirst.waiting and show the count in a small line.
Send on reconnect
Call VoteFirst.send when your reachability reports a connection.
Say it in words
Map the codes you meet to one plain sentence each.
What to know before you ship
- The calls here were checked against package 0.3.0, and a minor release can change them.
- The queue sends only through the built in screens or your call to send. Nothing runs in the background.
- The limits are shared by every copy of your app, so many first time users at once can switch a budget off for sixty seconds.
- A write the server refuses is dropped from the queue, not kept.
iOS offline vote questions
Does the package keep a vote made with no network?
Yes. A network failure queues the write in a file, which survives the app being killed.
Must your own screens call send?
Only on your own screens. The built in screens send the queue when they appear and on pull to refresh.
Are failed requests retried?
Up to three attempts, for network failures, server errors and a short rate limit wait. A refused request is not retried.
What if the app is opened for the first time with no network?
The write is queued anyway and the voter is minted when the queue drains.
Is anything retried in the background?
No. The queue is sent by the built in screens or by your call to send.
What happens past the project limits?
That budget turns off for your whole project for sixty seconds, and requests answer rateLimited.
Does it need iOS 15?
Yes, or macOS 12. There is no Android build.
What does it cost?
The package is free to use. Free holds one project and 100 votes. Past that, an offline feedback screen runs on Lite at $9/mo or Pro at $39/mo, after a 14 day trial with no card.
More ways to add a board
More for apps that ship on the App Store.
A SwiftUI feedback form
The board, votes and a suggestion form.
Single sign on
Votes under your users' own names.
Feature voting for iOS apps
The board inside your app.
FeedbackThread or VoteFirst for your app
FeedbackThread pulls in reviews; VoteFirst ranks by who pays.
Test a SwiftUI feedback screen
Stub the network, go offline and keep previews harmless.
Native or WebView feedback SDKs
Which kits draw SwiftUI and which load a web page.
Offline and retries
What the package does about lost signal and duplicate presses.
CocoaPods trunk goes read only on 2 December
103,896 pods counted, and what stops on the day.
Make votes survive a bad signal
Free starts with one project, 100 votes. When an offline feedback screen outgrows it, Lite is $9/mo and Pro is $39/mo, each after a 14 day trial with no card.