When an API answers a POST with 422 and a JSON message, URLSession doesn't throw, and Alamofire without validate() calls the success handler. Check the status code yourself, decode the message and the per-field errors with Codable, and show each error under its own field. Also send the body in the format the API reads: in a test, a server that reads form fields answered "All fields are required" to a JSON body with every field filled in.
SWIFT TIPS · UIKIT · URLSESSION
First posted on July 25, 2018, as "Print Message in Post Password Alamofire". Rewritten on November 18, 2026. The requests were run on a Mac against a local test server on 127.0.0.1 with sample passwords and a sample token, with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The test server copies the 2018 API's answers but isn't that API. The screen was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.
In 2018 I had a Change Password screen with three fields: the current password, the new one, and the new one again. The post first tried the endpoint in Postman, with the Body tab set to form-data, and showed the answer: status 422, the message "All fields are required", and an errors object with one message per field. Then came the code: an Alamofire POST with JSONEncoding.default, the token from UserDefaults in the Authorization header, and a success handler that printed the message and the status.
The post set out to print the message, and it did. Two details are worth a closer look, because they decide whether users ever see that message.
A 422 lands in the success branch
Alamofire's documentation says that by default it treats any completed request as successful, whatever the response says, and that calling validate() turns a status outside 200 to 299 into an error. The 2018 code had no validate(), so a rejected password change and a successful one both arrived in .success and went to the same print.
URLSession works the same way. Its data(for:) throws for transport problems, such as no connection or a cancelled task. A 422 is a normal answer that comes back with its status code, as the first line of the test below shows. Whichever library you use, the app has to look at the status code.
Postman sent a form, the code sent JSON
The screenshot shows Postman's form-data option, which sends form fields. JSONEncoding.default sends a JSON body. Many servers read both, but a server that only reads form fields finds no fields in a JSON body. I can't know which kind the 2018 server was; the 422 in the post came from Postman with empty values. So I made a test server that reads form fields only and wants Bearer in front of the token:
Test server reads form fields only and wants "Bearer <token>".
JSON body, all three fields filled: HTTP 422 {"status_code": 422, "message": "All fields are required", "errors": {"old_password": "The old_password field is required.", "password": "The password field is required.", "verifypassword": "The verifypassword field is required."}}
JSON body, token without "Bearer": HTTP 401 {"status_code": 401, "message": "Unauthenticated."}
ChangePasswordService, form body, right values: success, "Password changed."
ChangePasswordService, form body, wrong current password: "Please check the form.", field errors ["old_password: The old password is wrong."]
ChangePasswordService, form body, empty new password: "All fields are required", field errors ["password: The password field is required.", "verifypassword: The verifypassword field is required."]
ChangePasswordService, form body, expired token: Your session has ended. Please sign in again.
- Same fields, wrong format. The JSON body had all three passwords filled in, and the server still answered "All fields are required", because it never looked inside JSON. From the app, that looks like a server bug.
- The token format matters too. The 2018 code sent the stored token as it was. This server wanted
Bearerin front and answered 401 without it. What your API wants is in Postman's Authorization tab; copy that exactly. - The new service sends a form body. It returned the success message for the right values, a field error for a wrong current password, field errors for empty fields, and a "please sign in again" error for an expired token.
The service
import Foundation
/// Builds an application/x-www-form-urlencoded body, the format Postman's form tab sends.
enum FormBody {
private static let allowed = CharacterSet(charactersIn:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
static func encode(_ fields: [(String, String)]) -> Data {
let pairs = fields.map { name, value in
"\(name.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")=\(value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")"
}
return Data(pairs.joined(separator: "&").utf8)
}
}
/// The API's JSON for both success and errors:
/// {"status_code": 422, "message": "...", "errors": {"password": "..."}}
struct APIMessage: Decodable, Sendable {
let message: String
let errors: [String: String]?
}
enum ChangePasswordError: LocalizedError {
case invalid(message: String, fieldErrors: [String: String])
case signedOut
case server(status: Int)
var errorDescription: String? {
switch self {
case .invalid(let message, _): return message
case .signedOut: return "Your session has ended. Please sign in again."
case .server(let status): return "The server answered with status \(status). Please try again."
}
}
}
struct ChangePasswordService: Sendable {
let url: URL
var session: URLSession = .shared
/// Returns the server's success message, or throws `ChangePasswordError`.
func change(old: String, new: String, confirm: String, token: String) async throws -> String {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = FormBody.encode([("old_password", old), ("password", new), ("verifypassword", confirm)])
// URLSession doesn't throw for a 4xx or 5xx status: check it yourself.
let (data, response) = try await session.data(for: request)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
let body = try? JSONDecoder().decode(APIMessage.self, from: data)
switch status {
case 200..<300:
return body?.message ?? "Password changed."
case 401:
throw ChangePasswordError.signedOut
case 400, 422:
throw ChangePasswordError.invalid(message: body?.message ?? "Please check the form.",
fieldErrors: body?.errors ?? [:])
default:
throw ChangePasswordError.server(status: status)
}
}
}
The screen
import UIKit
final class ChangePasswordViewController: UIViewController {
@MainActor private struct Row {
let key: String // the API's field name
let field = UITextField()
let error = UILabel()
}
private let rows = [Row(key: "old_password"), Row(key: "password"), Row(key: "verifypassword")]
private let sendButton = UIButton(configuration: .filled())
private let service: ChangePasswordService
private let token: () -> String? // read from the Keychain, not UserDefaults
init(service: ChangePasswordService, token: @escaping () -> String?) {
self.service = service
self.token = token
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
title = "Password"
let placeholders = ["Current password", "New password", "Repeat new password"]
let stack = UIStackView()
stack.axis = .vertical
stack.spacing = 6
for (index, row) in rows.enumerated() {
row.field.placeholder = placeholders[index]
row.field.isSecureTextEntry = true
row.field.textContentType = index == 0 ? .password : .newPassword
row.field.borderStyle = .roundedRect
row.error.font = .preferredFont(forTextStyle: .footnote)
row.error.textColor = .systemRed
row.error.numberOfLines = 0
row.error.isHidden = true
stack.addArrangedSubview(row.field)
stack.addArrangedSubview(row.error)
stack.setCustomSpacing(16, after: row.error)
}
sendButton.configuration?.title = "Change Password"
sendButton.addAction(UIAction { [weak self] _ in self?.send() }, for: .touchUpInside)
stack.addArrangedSubview(sendButton)
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24),
stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
])
}
private func show(_ errors: [String: String]) {
for row in rows {
row.error.text = errors[row.key]
row.error.isHidden = errors[row.key] == nil
}
}
private func send() {
let values = rows.map { $0.field.text ?? "" }
// Check what the app can check by itself before asking the server.
var errors: [String: String] = [:]
for (row, value) in zip(rows, values) where value.isEmpty { errors[row.key] = "Required." }
if errors.isEmpty, values[1] != values[2] { errors["verifypassword"] = "The passwords don't match." }
show(errors)
guard errors.isEmpty else { return }
guard let token = token() else { return showAlert(ChangePasswordError.signedOut.localizedDescription) }
sendButton.isEnabled = false
sendButton.configuration?.showsActivityIndicator = true
Task { [weak self, service] in
defer {
self?.sendButton.isEnabled = true
self?.sendButton.configuration?.showsActivityIndicator = false
}
do {
let message = try await service.change(old: values[0], new: values[1], confirm: values[2], token: token)
self?.rows.forEach { $0.field.text = nil }
self?.showAlert(message)
} catch ChangePasswordError.invalid(_, let fieldErrors) where !fieldErrors.isEmpty {
self?.show(fieldErrors) // each message under its own field
} catch {
self?.showAlert(error.localizedDescription)
}
}
}
private func showAlert(_ message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)
}
}
How it works
- The status code decides. 200 to 299 returns the server's message. 401 means the token is no longer valid, so the user should sign in again. 400 and 422 carry the message and the field errors. Anything else is a server problem with a generic message.
- Errors appear under their fields. The
errorsobject is keyed by the API's field names, and each row on the screen knows its key, soshow(_:)puts "The old password is wrong." under the current password field. Hidden labels take no space in the stack view. - What the app can check, it checks first. Empty fields and a mismatched repeat are caught before any request. The server still checks everything; it's the one that decides.
- Password AutoFill. Apple's guide says to set
textContentTypeso a field shows the right AutoFill suggestions. The current password is.passwordand the two new ones are.newPassword. - The token comes from a closure. Read it from the Keychain there. The 2018 code read it from
UserDefaults, which isn't meant for secrets. - The form body is encoded.
FormBodypercent-encodes everything except letters, digits and-._~, so a password with+or&arrives unchanged. The login post linked below tests that.
A quick check for your project
- Find your POST calls and check what happens on a 422. If it reaches the same code as a 200, add a status check or
validate(). - Compare Postman's Body tab with the encoding in your code: form-data or x-www-form-urlencoded means a form body, raw JSON means
application/json. - Search for
UserDefaultsand "token" in the same line, and move tokens to the Keychain.
What the 2018 version said
The fields were AnimatedTextInput views from a CocoaPod, the same library as the floating-label post linked below. Each field was checked with a guard that returned silently when it was empty, so an empty form did nothing visible. The Postman screenshot shows the form-data keys with no values, which is why the 422 listed all three fields:

Keep reading on JR Devhub
Comments