← Integrations

Mobile app · Swift, Python

A dasha timeline in Swift: URLSession, Codable and birth time zones

An iOS app sends birth details to your server and gets back the mahadasha list; your server holds the AstroNode key. The Swift below ran against a backend that called the API - and the part that most often goes wrong is not the HTTP, it is the tz_offset_minutes you send.

Updated

How this page was checked: Executed: the Swift client and birthInput (Swift 6.4, Foundation URLSession + Codable) against the Python backend below, which called the in-memory API with urllib. Not executed: SwiftUI view rendering.

The backend

Nothing secret ships in an .ipa: strings in Info.plist, an .xcconfig or the binary can all be extracted. The app calls your server; this Python helper (standard library only, so it drops into Django, Flask or FastAPI) calls AstroNode and returns the mahadasha list.

python
import json
import os
import urllib.error
import urllib.request

BASE = os.environ.get("ASTRONODE_BASE_URL", "https://api.astronode.dev")


def astronode_post(path, body, timeout=15):
    req = urllib.request.Request(
        BASE + path,
        data=json.dumps(body).encode(),
        headers={
            "Authorization": "Bearer " + os.environ["ASTRONODE_API_KEY"],
            "Content-Type": "application/json",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as res:
            return res.status, json.load(res)
    except urllib.error.HTTPError as err:
        return err.code, json.load(err)


def mahadashas(birth):
    """What the iOS app's /dasha endpoint returns: the mahadasha list only."""
    status, payload = astronode_post("/v1/dasha/vimshottari", {**birth, "levels": 1})
    if status != 200:
        return status, {"code": payload["error"]["code"]}
    return 200, {"periods": payload["data"]["mahadasha"]}

levels: 1 returns mahadashas only; the default nests antardashas inside each one, which a timeline screen does not need on first load.

Codable models and the request

swift
import Foundation

struct Birth: Encodable {
    let date: String            // "1973-04-24"
    let time: String            // "17:25:00", local wall-clock time
    let tz_offset_minutes: Int  // 330 for IST
    let lat: Double
    let lng: Double
}

struct Period: Decodable, Identifiable {
    let lord: String
    let start: Date
    let end: Date
    let years: Double
    var id: Date { start }
}

private struct PeriodsResponse: Decodable { let periods: [Period] }

enum DashaClient {
    // Your backend - never api.astronode.dev, and never the API key.
    static let backend = URL(string: "https://api.your-app.example.com/dasha")!

    static let decoder: JSONDecoder = {
        let d = JSONDecoder()
        let withFraction = ISO8601DateFormatter()
        withFraction.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        d.dateDecodingStrategy = .custom { decoder in
            let s = try decoder.singleValueContainer().decode(String.self)
            guard let date = withFraction.date(from: s) else {
                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath,
                    debugDescription: "Not an ISO 8601 date: \(s)"))
            }
            return date
        }
        return d
    }()

    static func mahadashas(for birth: Birth) async throws -> [Period] {
        var req = URLRequest(url: backend)
        req.httpMethod = "POST"
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        req.httpBody = try JSONEncoder().encode(birth)
        let (data, response) = try await URLSession.shared.data(for: req)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }
        return try decoder.decode(PeriodsResponse.self, from: data).periods
    }
}

Period boundaries come back with milliseconds ("2014-04-04T13:57:40.720Z") because dasha years are fractional. Foundation's stock .iso8601 strategy has historically rejected fractional seconds; the custom strategy above decodes them on every OS version you are likely to support. years is a Double for the same reason: the first period is the balance left at birth (5.94 years for the sample).

For the sample birth (24 April 1973, 17:25, Mumbai) the call returned 10 mahadashas, and the one running on 1 December 2026 was Jupiter, 2014-04-04 → 2030-04-04. In SwiftUI, List(periods) { p in ... } works directly because Period is Identifiable.

The mistake that bites first: today's offset instead of the birth's

TimeZone.current.secondsFromGMT() is the offset of the phone, now. The API needs the offset that was in force at the birthplace on the birth date. Those differ whenever the user was born somewhere else, or in a different daylight-saving period - and an hour's error moves the ascendant and shifts every dasha date.

swift
func birthInput(local: DateComponents, place: TimeZone, lat: Double, lng: Double) -> Birth {
    var cal = Calendar(identifier: .gregorian)
    cal.timeZone = place
    let instant = cal.date(from: local)!
    let offset = place.secondsFromGMT(for: instant) / 60   // the offset in force at birth
    return Birth(
        date: String(format: "%04d-%02d-%02d", local.year!, local.month!, local.day!),
        time: String(format: "%02d:%02d:%02d", local.hour!, local.minute!, local.second ?? 0),
        tz_offset_minutes: offset, lat: lat, lng: lng)
}
Executed results
Inputtz_offset_minutes
New York, 15 July 1990, 14:30 (America/New_York)-240 (daylight time)
America/New_York offset on 1 Dec 2026-300 - what a "current offset" shortcut would send
Mumbai, 24 April 1973, 17:25 (Asia/Kolkata)330

Resolve the birthplace to a TimeZone identifier on your backend or with a geocoder when the user picks the city, then let Foundation's time-zone database supply the historical offset. More on why this matters in birth time and time zones.

Questions

Which AstroNode endpoints does the Swift (iOS) example call?
1 endpoint: Vimshottari Dasha (POST /v1/dasha/vimshottari).
Was the Swift (iOS) code on this page actually run?
Executed: the Swift client and birthInput (Swift 6.4, Foundation URLSession + Codable) against the Python backend below, which called the in-memory API with urllib. Not executed: SwiftUI view rendering.