Short answer

You can send a login form without Alamofire or SwiftyJSON: build a URLRequest with POST, the application/x-www-form-urlencoded content type and a body you encode yourself, send it with URLSession's async data(for:), and decode the JSON answer into a Decodable struct. Percent-encode every character except ASCII letters, digits and -._~. If you build the body with string interpolation, a password with + or & arrives at the server changed, and the login fails for that user.

SWIFT TIPS · UIKIT · URLSESSION

First posted on April 21, 2018 for Swift 4, as "Login Use Alamofire And SwiftyJSON (Swift 4)". Rewritten on November 18, 2026. The login service was run on a Mac against a local test server on 127.0.0.1 with a sample account, with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. No real server or account was used. The view controller 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 my login screen used Alamofire and SwiftyJSON. The button action read the email and password fields, returned early if either was empty, sent them as form parameters with Alamofire.request(..., method: .post, encoding: URLEncoding.default), checked for a 200 to 299 status, and pushed the home tab bar on success. On failure it showed an alert.

Alamofire handled the form encoding correctly, so that code didn't have the bug below. But URLSession with async/await and Codable now does this job in a few dozen lines, without two libraries, and the body is the easiest part to get wrong.

What a server reads from a hand-built body

I ran a small server on my Mac that decodes form bodies the standard way (Python's parse_qs) and answers with what it read. Then I sent the sample password a+b&c=d three ways:

Password typed: "a+b&c=d"

1. String interpolation
  sent: email=test@example.com&password=a+b&c=d
  server read: c="d"  email="test@example.com"  password="a b"
2. URLComponents.percentEncodedQuery
  sent: email=test@example.com&password=a+b%26c%3Dd
  server read: email="test@example.com"  password="a b&c=d"
3. FormBody.encode
  sent: email=test%40example.com&password=a%2Bb%26c%3Dd
  server read: email="test@example.com"  password="a+b&c=d"
4. FormBody.encode, password "caf\u{E9}+1" (an accented e)
  sent: email=test%40example.com&password=caf%C3%A9%2B1
  server read the same password: true

LoginService against the local /login endpoint:
  right password: token sample-token-123, user Test User
  wrong password: Wrong email or password.
  • String interpolation broke it twice. In a form body, + means a space and & starts a new field. The server read the password as "a b" and got an extra field called c.
  • URLComponents got halfway. It encoded & and = but left + alone, because + is allowed in a URL query. In a form body it still means a space, so the server read "a b&c=d". The WHATWG URL standard's form decoding step replaces every + with a space.
  • FormBody.encode kept it exact. It percent-encodes everything except ASCII letters, digits and -._~, so + became %2B and the server read a+b&c=d. A password with an accented letter also arrived unchanged: the é was sent as %C3%A9, its two UTF-8 bytes.

The last lines are the login service below, against the same server: a sample token for the right password, and the server's own message for a wrong one.

The login service

import Foundation

/// Builds an application/x-www-form-urlencoded body, the format the 2018 Alamofire call sent.
enum FormBody {
    // ASCII letters, digits and - . _ ~ stay as they are. Everything else, including + & = spaces
    // and non-ASCII letters, is percent-encoded, so a password like "a+b&c=d" arrives unchanged.
    private static let allowed = CharacterSet(charactersIn:
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")

    static func encode(_ fields: [(String, String)]) -> Data {
        let pairs = fields.map { name, value in
            let n = name.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
            let v = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
            return "\(n)=\(v)"
        }
        return Data(pairs.joined(separator: "&").utf8)
    }
}

struct LoginResponse: Decodable, Sendable {
    struct User: Decodable, Sendable { let name: String }
    let token: String
    let user: User
}

enum LoginError: LocalizedError {
    case wrongCredentials(String)
    case server(status: Int)

    var errorDescription: String? {
        switch self {
        case .wrongCredentials(let message): return message
        case .server(let status): return "The server answered with status \(status). Please try again."
        }
    }
}

struct LoginService: Sendable {
    let loginURL: URL
    var session: URLSession = .shared

    func logIn(email: String, password: String) async throws -> LoginResponse {
        var request = URLRequest(url: loginURL)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = FormBody.encode([("email", email), ("password", password)])

        let (data, response) = try await session.data(for: request)
        let status = (response as? HTTPURLResponse)?.statusCode ?? 0
        switch status {
        case 200..<300:
            return try JSONDecoder().decode(LoginResponse.self, from: data)
        case 400, 401, 422:
            struct Message: Decodable { let message: String }
            let message = (try? JSONDecoder().decode(Message.self, from: data))?.message
            throw LoginError.wrongCredentials(message ?? "Check your email and password.")
        default:
            throw LoginError.server(status: status)
        }
    }
}

The login screen

import UIKit

final class LoginViewController: UIViewController {
    private let emailField = UITextField()
    private let passwordField = UITextField()
    private let loginButton = UIButton(configuration: .filled())
    private let service = LoginService(loginURL: URL(string: "https://api.example.com/ios/v1/auth/login")!)

    var onLoggedIn: ((LoginResponse) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground

        emailField.placeholder = "Email"
        emailField.keyboardType = .emailAddress
        emailField.textContentType = .username
        emailField.autocapitalizationType = .none
        emailField.autocorrectionType = .no
        passwordField.placeholder = "Password"
        passwordField.isSecureTextEntry = true
        passwordField.textContentType = .password
        for field in [emailField, passwordField] { field.borderStyle = .roundedRect }

        loginButton.configuration?.title = "Log In"
        loginButton.addAction(UIAction { [weak self] _ in self?.logIn() }, for: .touchUpInside)

        let stack = UIStackView(arrangedSubviews: [emailField, passwordField, loginButton])
        stack.axis = .vertical
        stack.spacing = 12
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
            stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
        ])
    }

    private func logIn() {
        let email = (emailField.text ?? "").trimmingCharacters(in: .whitespaces)
        let password = passwordField.text ?? ""
        guard !email.isEmpty, !password.isEmpty else {
            showMessage("Enter your email and password.")
            return
        }

        loginButton.configuration?.showsActivityIndicator = true
        loginButton.isEnabled = false
        // The button stays disabled until the request ends, so a second tap can't send it twice.
        Task { [weak self] in
            guard let self else { return }
            defer {
                loginButton.configuration?.showsActivityIndicator = false
                loginButton.isEnabled = true
            }
            do {
                let response = try await service.logIn(email: email, password: password)
                onLoggedIn?(response)
            } catch {
                showMessage(error.localizedDescription)
            }
        }
    }

    private func showMessage(_ text: String) {
        let alert = UIAlertController(title: nil, message: text, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

How it works

  • Decodable instead of SwiftyJSON. LoginResponse describes the JSON the server sends. If a field is missing or has the wrong type, decoding throws, instead of quietly giving you an empty string.
  • Status codes decide the error. 200 to 299 is success. 400, 401 and 422 are "wrong input", and the server's message is shown when it sends one. Anything else is a server problem with a generic message. That replaces Alamofire's .validate(statusCode: 200..<300).
  • The button shows the wait. showsActivityIndicator puts a spinner in the button and isEnabled = false stops a second tap from sending the request twice. defer turns both back when the request ends, whichever way it ends.
  • Empty fields get a message. The 2018 guard statements returned silently, so tapping Log In with an empty field did nothing visible.
  • Password AutoFill. textContentType set to .username and .password tells iOS which fields to fill from saved passwords.
  • Navigation is the caller's job. onLoggedIn hands the response back. Where the token is stored and which screen comes next belong to the app's flow; the post linked below shows the Keychain and the "already signed in" check.

A few things to keep out of a login screen

  • Printing the response. The 2018 code printed the whole response with print("isi: \(data)"). A login response usually holds a token, and anyone who can see the console output can read it. Don't print it.
  • Tokens in UserDefaults. Store tokens in the Keychain, not in UserDefaults.
  • Plain http://. Use https://. App Transport Security blocks plain HTTP connections by default, and a password should never travel unencrypted anyway.

A quick check for your project

  1. Search for httpBody = and look at how the body string is built. Any \(password) or \(email) in it needs encoding.
  2. Try logging in with a test account whose password contains +, &, = and a space.
  3. Search for print( near login and token code and remove anything that prints a response or a header.

What the 2018 version said

The original sent the request to a placeholder address, https://yourbaseUrl/ios/v1/auth/login, and pushed HomeTabBarController() onto the navigation controller on success. Its failure branch used an alert constant that the snippet doesn't create.

Sources