Add Prayer Times to Your iOS App with Swift
This post shows you how to build a prayer times screen in SwiftUI. You will get the user's GPS coordinates, fetch today's times from UmmahAPI, display them in a list, and fire a local notification before each prayer.
What You Need
Before writing any code, make sure you have:
- Xcode 16 or later
- iOS 17 deployment target (the APIs used here are available on iOS 16+, but 17 is a safe baseline)
- A free UmmahAPI key from ummahapi.com/register. You can skip the key to start. Without one you get 5,000 requests per 15 minutes, which is plenty for testing.
No third-party packages are needed. Everything here uses Apple frameworks that ship with the SDK: CoreLocation, UserNotifications, and Swift's built-in URLSession.
Project Setup
Create a new SwiftUI project in Xcode. Call it whatever you like. Then add two keys to your Info.plist:
NSLocationWhenInUseUsageDescriptionwith a string like "Used to find prayer times for your location."NSUserNotificationsUsageDescriptionis not a real plist key. Notification permission is requested at runtime, so you do not need a plist entry for it.
That is the only plist change needed. The rest is Swift code.
Getting the User's Location
Create a file called LocationManager.swift. This class wraps CLLocationManager and publishes the latest coordinates so SwiftUI views can react to changes.
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
@Published var latitude: Double?
@Published var longitude: Double?
@Published var authStatus: CLAuthorizationStatus = .notDetermined
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyKilometer
}
func requestPermission() {
manager.requestWhenInUseAuthorization()
}
func start() {
manager.startUpdatingLocation()
}
func locationManager(
_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]
) {
guard let loc = locations.last else { return }
latitude = loc.coordinate.latitude
longitude = loc.coordinate.longitude
manager.stopUpdatingLocation() // one fix is enough
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
authStatus = manager.authorizationStatus
if authStatus == .authorizedWhenInUse || authStatus == .authorizedAlways {
start()
}
}
}
Using kCLLocationAccuracyKilometer is fine here. Prayer times do not need GPS precision down to the meter.
Fetching Prayer Times from UmmahAPI
Create a file called PrayerTimesService.swift. This handles the network call and decodes the JSON response from the prayer times endpoint.
The endpoint is:
GET https://ummahapi.com/api/prayer-times?lat=21.42&lng=39.82
The response includes fields named Fajr, Sunrise, Dhuhr, Asr, Maghrib, and Isha as time strings like "05:14". Here is a model and a service that decodes them:
import Foundation
struct PrayerTimes: Decodable {
let Fajr: String
let Sunrise: String
let Dhuhr: String
let Asr: String
let Maghrib: String
let Isha: String
var all: [(name: String, time: String)] {
[
("Fajr", Fajr),
("Sunrise", Sunrise),
("Dhuhr", Dhuhr),
("Asr", Asr),
("Maghrib", Maghrib),
("Isha", Isha)
]
}
}
struct PrayerTimesResponse: Decodable {
let data: PrayerTimes
}
class PrayerTimesService {
func fetch(lat: Double, lng: Double) async throws -> PrayerTimes {
var components = URLComponents(string: "https://ummahapi.com/api/prayer-times")!
components.queryItems = [
URLQueryItem(name: "lat", value: "\(lat)"),
URLQueryItem(name: "lng", value: "\(lng)")
]
let (data, _) = try await URLSession.shared.data(from: components.url!)
let decoded = try JSONDecoder().decode(PrayerTimesResponse.self, from: data)
return decoded.data
}
}
Tip. If you have a free API key, add it as a query item: URLQueryItem(name: "key", value: "YOUR_KEY"). This removes the shared rate limit and ties requests to your account.
Building the SwiftUI View
Now wire the location manager and the service into a view. Create PrayerTimesView.swift.
import SwiftUI
struct PrayerTimesView: View {
@StateObject private var location = LocationManager()
@State private var times: PrayerTimes?
@State private var isLoading = false
@State private var errorMessage: String?
private let service = PrayerTimesService()
var body: some View {
NavigationStack {
Group {
if isLoading {
ProgressView("Loading prayer times...")
} else if let times {
List(times.all, id: \.name) { prayer in
HStack {
Text(prayer.name).fontWeight(.semibold)
Spacer()
Text(prayer.time).foregroundStyle(.secondary)
}
}
} else if let errorMessage {
Text(errorMessage).foregroundStyle(.red).padding()
} else {
Text("Waiting for location...").foregroundStyle(.secondary)
}
}
.navigationTitle("Prayer Times")
}
.onAppear {
location.requestPermission()
}
.onChange(of: location.latitude) { _, lat in
guard let lat, let lng = location.longitude else { return }
Task { await loadTimes(lat: lat, lng: lng) }
}
}
private func loadTimes(lat: Double, lng: Double) async {
isLoading = true
errorMessage = nil
do {
times = try await service.fetch(lat: lat, lng: lng)
} catch {
errorMessage = "Could not load times. Check your connection."
}
isLoading = false
}
}
The onChange(of:) modifier fires when the location manager publishes a latitude. At that point both coordinates are ready, so you kick off the network call.
Scheduling Local Notifications
The API returns times as strings like "05:14". You need to convert each string into a DateComponents and then schedule a UNCalendarNotificationTrigger. Create NotificationScheduler.swift.
import UserNotifications
class NotificationScheduler {
func requestPermission() async -> Bool {
let center = UNUserNotificationCenter.current()
let granted = try? await center.requestAuthorization(options: [.alert, .sound])
return granted ?? false
}
func schedule(times: PrayerTimes) {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: times.all.map { $0.name })
for prayer in times.all {
guard let components = parseTime(prayer.time) else { continue }
let content = UNMutableNotificationContent()
content.title = prayer.name
content.body = "It is time for \(prayer.name)."
content.sound = .default
let trigger = UNCalendarNotificationTrigger(
dateMatching: components,
repeats: false
)
let request = UNNotificationRequest(
identifier: prayer.name,
content: content,
trigger: trigger
)
center.add(request)
}
}
private func parseTime(_ timeString: String) -> DateComponents? {
let parts = timeString.split(separator: ":").compactMap { Int($0) }
guard parts.count == 2 else { return nil }
var components = Calendar.current.dateComponents([.year, .month, .day], from: Date())
components.hour = parts[0]
components.minute = parts[1]
components.second = 0
return components
}
}
Call scheduler.schedule(times: times) right after the fetch succeeds. The trigger fires once today at the given hour and minute. If you want daily repeats, change repeats to true and strip the year, month, and day components so the trigger matches any day at that time.
Tip. The API times use the 24-hour format. The parseTime function above handles that correctly since it reads the raw integer values, not AM/PM strings.
Putting the Scheduler Into the View
Update loadTimes in your view to call the scheduler after a successful fetch:
private let scheduler = NotificationScheduler()
private func loadTimes(lat: Double, lng: Double) async {
isLoading = true
errorMessage = nil
do {
times = try await service.fetch(lat: lat, lng: lng)
let allowed = await scheduler.requestPermission()
if allowed, let times {
scheduler.schedule(times: times)
}
} catch {
errorMessage = "Could not load times. Check your connection."
}
isLoading = false
}
Permission is requested once. iOS caches the user's choice, so requestAuthorization only shows the system dialog the first time. After that it returns the stored preference immediately.
Fetching a Full Month of Times
The API also supports monthly data. Pass month and year query parameters and you get back an array of daily times. This is useful if you want to cache data locally so the app works offline.
func fetchMonth(lat: Double, lng: Double, month: Int, year: Int) async throws -> [PrayerTimes] {
var components = URLComponents(string: "https://ummahapi.com/api/prayer-times")!
components.queryItems = [
URLQueryItem(name: "lat", value: "\(lat)"),
URLQueryItem(name: "lng", value: "\(lng)"),
URLQueryItem(name: "month", value: "\(month)"),
URLQueryItem(name: "year", value: "\(year)")
]
let (data, _) = try await URLSession.shared.data(from: components.url!)
// The monthly response wraps an array in the "data" key
struct MonthResponse: Decodable { let data: [PrayerTimes] }
let decoded = try JSONDecoder().decode(MonthResponse.self, from: data)
return decoded.data
}
Store the returned array in UserDefaults or a local JSON file. Then on each app launch, load from disk first and fetch fresh data in the background. This keeps the UI responsive even without network access.
Testing Without a Device
The Xcode simulator can simulate a location. Go to Features > Location in the menu while the simulator is running. Pick a preset city or enter custom coordinates. The CLLocationManager will fire with that fake location, and the rest of the app works normally.
To test notifications in the simulator, trigger them manually. After scheduling, run this in Xcode's debug console to advance the simulator clock, or just wait. For quick testing, reduce the trigger time to one minute ahead using a UNTimeIntervalNotificationTrigger instead of a calendar trigger.
FAQ
How do I get the user's location in a SwiftUI app?
Use the CoreLocation framework. Create a CLLocationManager, call requestWhenInUseAuthorization(), and read coordinates in the locationManager(_:didUpdateLocations:) delegate method. Add NSLocationWhenInUseUsageDescription to your Info.plist with a description string.
What endpoint do I call to get prayer times from UmmahAPI?
Call GET https://ummahapi.com/api/prayer-times?lat=YOUR_LAT&lng=YOUR_LNG with the user's coordinates. The response includes Fajr, Sunrise, Dhuhr, Asr, Maghrib, and Isha as time strings. See the full Prayer Times API page for all options.
Can I schedule local notifications for each prayer time in Swift?
Yes. Use UNUserNotificationCenter from the UserNotifications framework. Parse the prayer time string into a DateComponents value, then create a UNCalendarNotificationTrigger for each prayer and add it via UNUserNotificationCenter.current().add(_:).
Does UmmahAPI require an API key?
No. You can call the endpoints without a key and get 5,000 requests per 15 minutes. Register for a free key to remove that limit and get access to usage analytics.
Free prayer times data for your iOS app
UmmahAPI gives you prayer times, Quran, Hadith, Qibla direction, and more in one free API.
Read the docs