I'll walk you through creating a simple alarm app in SwiftUI, breaking down the process step by step:
Alarm App Design Concept
We'll create an alarm app with the following features:
- Set an alarm time
- Enable/disable the alarm
- Play a sound when the alarm triggers
- Simple, clean user interface
Step-by-Step Implementation
1. Create the Data Model
First, we'll define an Alarm struct to represent our alarm:
swift
import Foundation
struct Alarm: Identifiable {
let id = UUID()
var time: Date
var isEnabled: Bool
var label: String
}
2. Create the View Model
Next, we'll create a view model to manage alarm logic:
swift
import Foundation
import UserNotifications
class AlarmViewModel: ObservableObject {
@Published var alarms: [Alarm] = []
func addAlarm(time: Date, label: String) {
let newAlarm = Alarm(time: time, isEnabled: true, label: label)
alarms.append(newAlarm)
}
func toggleAlarm(alarm: Alarm) {
if let index = alarms.firstIndex(where: { $0.id == alarm.id }) {
alarms[index].isEnabled.toggle()
}
}
func scheduleNotification(for alarm: Alarm) {
let content = UNMutableNotificationContent()
content.title = "Alarm"
content.body = alarm.label
content.sound = .default
// Extract time components
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute], from: alarm.time)
// Create trigger
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
// Create request
let request = UNNotificationRequest(identifier: alarm.id.uuidString, content: content, trigger: trigger)
// Add request to notification center
UNUserNotificationCenter.current().add(request)
}
}
3. Create the Main Alarm View
Now, we'll build the main view for our alarm app:
swift
import SwiftUI
struct AlarmView: View {
@StateObject private var viewModel = AlarmViewModel()
@State private var showingAddAlarm = false
@State private var selectedTime = Date()
@State private var alarmLabel = ""
var body: some View {
NavigationView {
List {
// Existing Alarms List
ForEach(viewModel.alarms) { alarm in
HStack {
VStack(alignment: .leading) {
Text(alarm.label)
.font(.headline)
Text(formatTime(alarm.time))
.font(.subheadline)
}
Spacer()
Toggle("", isOn: Binding(
get: { alarm.isEnabled },
set: { _ in viewModel.toggleAlarm(alarm: alarm) }
))
}
}
.onDelete(perform: deleteAlarm)
}
.navigationTitle("Alarms")
.navigationBarItems(trailing:
Button(action: { showingAddAlarm = true }) {
Image(systemName: "plus")
}
)
.sheet(isPresented: $showingAddAlarm) {
AddAlarmView(viewModel: viewModel, isPresented: $showingAddAlarm)
}
}
}
func formatTime(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter.string(from: date)
}
func deleteAlarm(at offsets: IndexSet) {
viewModel.alarms.remove(atOffsets: offsets)
}
}
struct AddAlarmView: View {
@ObservedObject var viewModel: AlarmViewModel
@Binding var isPresented: Bool
@State private var selectedTime = Date()
@State private var alarmLabel = ""
var body: some View {
NavigationView {
Form {
DatePicker("Select Time", selection: $selectedTime, displayedComponents: .hourAndMinute)
TextField("Alarm Label", text: $alarmLabel)
}
.navigationTitle("Add Alarm")
.navigationBarItems(
leading: Button("Cancel") { isPresented = false },
trailing: Button("Save") {
viewModel.addAlarm(time: selectedTime, label: alarmLabel.isEmpty ? "Alarm" : alarmLabel)
viewModel.scheduleNotification(for: viewModel.alarms.last!)
isPresented = false
}
)
}
}
}
struct ContentView: View {
var body: some View {
AlarmView()
}
}
Key Features Implemented
- Alarm Creation: Users can add new alarms with a time and optional label
- Alarm Toggling: Each alarm can be enabled or disabled
- Notification Scheduling: Uses
UNUserNotificationCenter to trigger alarms
- Simple UI: Clean, intuitive interface
Additional Setup Required
Before running the app, you'll need to:
- Request notification permissions in your
App struct
- Import necessary frameworks
swift
import SwiftUI
import UserNotifications
@main
struct AlarmApp: App {
init() {
requestNotificationPermissions()
}
func requestNotificationPermissions() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("Notification permissions granted")
} else if let error = error {
print(error.localizedDescription)
}
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Potential Improvements
- Add custom alarm sounds
- Create recurring alarm options
- Implement snooze functionality
- Add more detailed alarm settings
This implementation provides a solid foundation for a SwiftUI alarm app that you can further customize and expand upon.