### Clone and Setup Project
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/CONTRIBUTING.md
Clone the repository, navigate into the directory, set up the Node.js version, install dependencies, and run initial specs.
```bash
git clone https://github.com/sauravhiremath/react-native-ios-alarmkit.git
cd react-native-ios-alarmkit
nvm use
bun install
bun run specs
```
--------------------------------
### Install iOS Pods
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
After configuring Info.plist, navigate to the ios directory and install the necessary pods using the pod install command.
```bash
cd ios && pod install
```
--------------------------------
### Install react-native-ios-alarmkit
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Install the library using bun, npm, or yarn. Ensure react-native-nitro-modules is also installed.
```bash
# Using bun
bun add react-native-ios-alarmkit react-native-nitro-modules
# Using npm
npm add react-native-ios-alarmkit react-native-nitro-modules
# Using yarn
yarn add react-native-ios-alarmkit react-native-nitro-modules
```
--------------------------------
### Complete Example App with Hooks
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
This example demonstrates the full authorization flow, scheduling various alarm types, and managing active alarms using React hooks. It requires iOS 26+ and handles platform support checks.
```typescript
import React, { useCallback, useState } from 'react'
import { View, Text, Button, FlatList, Alert } from 'react-native'
import AlarmKit, {
useAlarms,
useAuthorizationState,
AlarmKitError,
} from 'react-native-ios-alarmkit'
export default function AlarmApp() {
const { state: authState, isLoading: authLoading } = useAuthorizationState()
const { alarms, isLoading: alarmsLoading } = useAlarms()
const [scheduling, setScheduling] = useState(false)
const handleRequestAuth = useCallback(async () => {
if (!AlarmKit.isSupported) {
Alert.alert('Not Supported', 'AlarmKit requires iOS 26+')
return
}
try {
await AlarmKit.requestAuthorization()
} catch (e) {
Alert.alert('Error', String(e))
}
}, [])
const handleScheduleTimer = useCallback(async () => {
setScheduling(true)
try {
const id = crypto.randomUUID()
await AlarmKit.scheduleTimer(id, {
duration: 10,
title: 'Quick Timer',
snoozeEnabled: false,
tintColor: '#5B7FA6',
})
Alert.alert('Success', 'Timer scheduled for 10 seconds')
} catch (e) {
if (e instanceof AlarmKitError) {
Alert.alert(`Error [${e.code}]`, e.message)
}
} finally {
setScheduling(false)
}
}, [])
const handleCancel = useCallback(async (id: string) => {
try {
await AlarmKit.cancel(id)
} catch (e) {
Alert.alert('Error', String(e))
}
}, [])
if (authLoading || alarmsLoading) {
return Loading...
}
return (
Platform Support: {AlarmKit.isSupported ? 'Yes' : 'No'}Authorization: {authState}
{authState !== 'authorized' && (
)}
{authState === 'authorized' && (
)}
Active Alarms: {alarms.length} item.id}
renderItem={({ item }) => (
{item.state}
)}
/>
)
}
```
--------------------------------
### Start Metro Bundler
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/example/README.md
Run this command from the root of your React Native project to start the Metro dev server. This is necessary for the app to build and run.
```sh
bun run start
```
--------------------------------
### Install CocoaPods Dependencies
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/example/README.md
Before running the iOS app, install CocoaPods dependencies. Run 'bundle install' first to install the Ruby bundler, then 'bundle exec pod install' to install native dependencies.
```sh
bundle install
```
```sh
bundle exec pod install
```
--------------------------------
### Test on iOS 26+
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/CONTRIBUTING.md
Install dependencies, set up CocoaPods, and run the project on iOS 26+ devices or simulators.
```bash
cd example
bun install
cd ios && pod install && cd ..
bun run ios
```
--------------------------------
### Build and Run iOS App
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/example/README.md
After installing CocoaPods dependencies, use this command to build and run the iOS application. Metro must be running in a separate terminal.
```sh
bun run ios
```
--------------------------------
### AlarmKit.countdown()
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Start the countdown for a scheduled alarm. Transitions the alarm from 'scheduled' state to 'countdown' state.
```APIDOC
## AlarmKit.countdown()
### Description
Start the countdown for a scheduled alarm. This action transitions the alarm from the 'scheduled' state to the 'countdown' state, initiating the timer.
### Method
`await` (asynchronous function)
### Endpoint
`AlarmKit.countdown(alarmId: string)`
### Parameters
#### Path Parameters
- **alarmId** (string) - Required - The unique identifier of the alarm to start the countdown for.
### Request Example
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
// Schedule an alarm for later
const alarmId = crypto.randomUUID()
await AlarmKit.scheduleAlarm(alarmId, {
hour: 14,
minute: 0,
title: 'Meeting Reminder',
})
// Start the countdown manually
await AlarmKit.countdown(alarmId)
console.log('Countdown started')
```
### Response
No explicit success response body. Success is indicated by the absence of an error.
```
--------------------------------
### Start an alarm countdown
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Transitions a scheduled alarm into the countdown state.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
// Schedule an alarm for later
const alarmId = crypto.randomUUID()
await AlarmKit.scheduleAlarm(alarmId, {
hour: 14,
minute: 0,
title: 'Meeting Reminder',
})
// Start the countdown manually
await AlarmKit.countdown(alarmId)
console.log('Countdown started')
```
--------------------------------
### Get Authorization State
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Gets the current authorization status for scheduling alarms. Returns 'notDetermined', 'authorized', or 'denied'.
```APIDOC
## AlarmKit.getAuthorizationState()
### Description
Get the current authorization status for scheduling alarms. Returns `'notDetermined'`, `'authorized'`, or `'denied'`.
### Usage
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
const state = await AlarmKit.getAuthorizationState()
switch (state) {
case 'authorized':
console.log('User has granted permission')
break
case 'denied':
console.log('User has denied permission - redirect to settings')
break
case 'notDetermined':
console.log('Permission not yet requested')
break
}
```
```
--------------------------------
### Get Authorization State
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Retrieve the current permission status for scheduling alarms.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
const state = await AlarmKit.getAuthorizationState()
switch (state) {
case 'authorized':
console.log('User has granted permission')
break
case 'denied':
console.log('User has denied permission - redirect to settings')
break
case 'notDetermined':
console.log('Permission not yet requested')
break
}
```
--------------------------------
### Get Alarms
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Retrieves all active alarms scheduled by the app. Returns an array of Alarm objects.
```APIDOC
## AlarmKit.getAlarms()
### Description
Retrieve all active alarms scheduled by the app. Returns an array of `Alarm` objects with id, state, countdown duration, and schedule information.
### Response
- **alarms** (array of Alarm objects) - An array containing all scheduled alarms.
- **Alarm object properties**:
- **id** (string) - The unique identifier for the alarm.
- **state** (string) - The current state of the alarm ('scheduled', 'countdown', 'paused', 'alerting').
- **countdownDuration** (object) - If applicable, details about pre-alert and post-alert durations.
- **preAlert** (number) - Duration in seconds before the main alert.
- **postAlert** (number) - Duration in seconds after the main alert.
- **schedule** (object) - Information about the alarm's schedule.
- **type** (string) - Type of schedule ('relative').
- **hour** (number) - The scheduled hour.
- **minute** (number) - The scheduled minute.
- **weekdays** (array of strings) - The days of the week the alarm is set for, or undefined for daily alarms.
### Usage
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
const alarms = await AlarmKit.getAlarms()
alarms.forEach(alarm => {
console.log(`Alarm ${alarm.id}:`)
console.log(` State: ${alarm.state}`) // 'scheduled' | 'countdown' | 'paused' | 'alerting'
if (alarm.countdownDuration) {
console.log(` Pre-alert: ${alarm.countdownDuration.preAlert}s`)
console.log(` Post-alert: ${alarm.countdownDuration.postAlert}s`)
}
if (alarm.schedule?.type === 'relative') {
console.log(` Time: ${alarm.schedule.hour}:${alarm.schedule.minute}`)
console.log(` Weekdays: ${alarm.schedule.weekdays?.join(', ') || 'daily'}`)
}
})
```
```
--------------------------------
### Get and Control Alarms
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Retrieve all scheduled alarms and control them using methods like cancel, pause, and resume. Each alarm or timer must have a unique ID.
```typescript
// Get all alarms
const alarms = await AlarmKit.getAlarms()
// Control alarms
await AlarmKit.cancel(timerId)
await AlarmKit.pause(timerId)
await AlarmKit.resume(timerId)
```
--------------------------------
### Configure Live Activities in Info.plist
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/docs/LIVE_ACTIVITY_SETUP.md
Add these keys to your widget extension's `Info.plist` file to enable Live Activities and frequent updates. This is crucial for the Live Activity to function correctly.
```xml
NSSupportsLiveActivitiesNSSupportsLiveActivitiesFrequentUpdates
```
--------------------------------
### Tagging a Release
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/CONTRIBUTING.md
Create a Git tag for a new release version.
```bash
git tag vX.Y.Z
```
--------------------------------
### Define Metadata and Widget Configuration in Swift
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/docs/LIVE_ACTIVITY_SETUP.md
Implement the AlarmMetadata protocol and configure the ActivityConfiguration to render the custom metadata in the Live Activity.
```swift
struct CookingMetadata: AlarmMetadata {
let iconName: String
let recipeName: String
}
struct AlarmLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: AlarmAttributes.self) { context in
VStack {
Image(systemName: context.attributes.metadata?.iconName ?? "alarm")
Text(context.attributes.metadata?.recipeName ?? "Alarm")
}
} dynamicIsland: { }
}
}
```
--------------------------------
### Development Commands
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/CONTRIBUTING.md
Run type checking, linting, and regenerate native specs. Ensure these commands pass before committing changes.
```bash
bun run typecheck # Type checking
```
```bash
bun run lint # ESLint
```
```bash
bun run specs # Regenerate native specs after *.nitro.ts
```
--------------------------------
### Simple API Methods
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Core methods for managing alarms, timers, and authorization states.
```APIDOC
## Simple API Methods
### Description
Methods to handle basic alarm and timer scheduling, authorization, and lifecycle management.
### Methods
- **AlarmKit.isSupported** (boolean) - Returns true if AlarmKit is available (iOS 26+).
- **AlarmKit.getAuthorizationState()** (Promise) - Returns current authorization status.
- **AlarmKit.requestAuthorization()** (Promise) - Requests user permission.
- **AlarmKit.scheduleTimer(id, config)** (Promise) - Schedules a countdown timer.
- **AlarmKit.scheduleAlarm(id, config)** (Promise) - Schedules a recurring alarm.
- **AlarmKit.cancel(id)** (Promise) - Cancels a scheduled alarm.
- **AlarmKit.stop(id)** (Promise) - Stops an alerting alarm.
- **AlarmKit.pause(id)** (Promise) - Pauses a countdown.
- **AlarmKit.resume(id)** (Promise) - Resumes a paused countdown.
- **AlarmKit.countdown(id)** (Promise) - Starts countdown for a scheduled alarm.
- **AlarmKit.getAlarms()** (Promise) - Retrieves all active alarms.
- **AlarmKit.addAlarmsListener(callback)** (Subscription) - Subscribes to alarm changes.
- **AlarmKit.addAuthorizationListener(callback)** (Subscription) - Subscribes to authorization changes.
```
--------------------------------
### Implement Live Activity UI in Swift
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/docs/LIVE_ACTIVITY_SETUP.md
This Swift code defines the UI for a Live Activity, including views for the lock screen and Dynamic Island. It requires the `ActivityKit`, `WidgetKit`, `SwiftUI`, and `AlarmKit` frameworks. Ensure your `AlarmAttributes` and `AlarmMetadata` are correctly defined.
```swift
import ActivityKit
import WidgetKit
import SwiftUI
import AlarmKit
struct AlarmLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: AlarmAttributes.self) {
context in
lockScreenView(context)
} dynamicIsland: {
context in
DynamicIsland {
DynamicIslandExpandedRegion(.leading) {
Image(systemName: "alarm")
.foregroundColor(context.attributes.tintColor)
}
DynamicIslandExpandedRegion(.trailing) {
Text(context.state.mode == .countdown ? "Countdown" : "Paused")
.font(.caption)
}
DynamicIslandExpandedRegion(.center) {
countdownText(context)
}
DynamicIslandExpandedRegion(.bottom) {
if context.state.mode == .countdown {
Text("Tap to pause")
.font(.caption2)
.foregroundColor(.secondary)
}
}
} compactLeading: {
Image(systemName: "alarm")
.foregroundColor(context.attributes.tintColor)
} compactTrailing: {
Text(timeRemaining(context))
.font(.caption2)
.monospacedDigit()
} minimal: {
Image(systemName: "alarm")
.foregroundColor(context.attributes.tintColor)
}
}
}
@ViewBuilder
func lockScreenView(_ context: ActivityViewContext>) -> some View {
VStack(spacing: 12) {
HStack {
Image(systemName: "alarm")
.foregroundColor(context.attributes.tintColor)
Text(context.attributes.presentation.alert.title)
.font(.headline)
.foregroundColor(context.attributes.tintColor)
}
countdownText(context)
.font(.title)
.monospacedDigit()
.foregroundColor(context.attributes.tintColor)
if context.state.mode == .paused {
Text("Paused")
.font(.caption)
.foregroundColor(.secondary)
}
}
.padding()
}
@ViewBuilder
func countdownText(_ context: ActivityViewContext>) -> some View {
if let date = context.state.date {
Text(timerInterval: date...Date.now, countsDown: false)
.multilineTextAlignment(.center)
} else {
Text("--:--")
}
}
func timeRemaining(_ context: ActivityViewContext>) -> String {
guard let date = context.state.date else { return "--:--" }
let interval = date.timeIntervalSince(Date.now)
let minutes = Int(interval) / 60
let seconds = Int(interval) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
}
struct EmptyMetadata: AlarmMetadata {}
```
--------------------------------
### Advanced API
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Advanced configuration using native AlarmKit mapping for complex alarm behaviors.
```APIDOC
## Advanced API
### Description
Provides 1:1 native AlarmKit mapping for full control over alarm configurations, including countdown and paused states.
### Usage
Use `AlarmConfigurationFactory` to build complex configurations and `AlarmKitManager.shared.schedule(id, config)` to apply them.
```
--------------------------------
### Run Checks Before Committing
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/CONTRIBUTING.md
Execute type checking and linting to ensure code quality and consistency before committing.
```bash
bun run typecheck && bun run lint
```
--------------------------------
### Advanced AlarmKitManager Configuration
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Demonstrates direct interaction with the native AlarmKit manager, including custom presentation attributes, metadata, and safe scheduling/cancellation methods.
```typescript
import { AlarmKitManager, AlarmConfigurationFactory } from 'react-native-ios-alarmkit'
// Create a fully customized timer configuration
const config = AlarmConfigurationFactory.timer({
duration: 300,
attributes: {
presentation: {
alert: {
title: 'Timer Done!',
stopButton: {
text: 'Stop',
textColor: '#FFFFFF',
systemImageName: 'stop.circle',
},
secondaryButton: {
text: 'Snooze',
textColor: '#FFFFFF',
systemImageName: 'zzz',
},
secondaryButtonBehavior: 'countdown',
},
countdown: {
title: 'Time Remaining',
pauseButton: {
text: 'Cancel',
textColor: '#FF6B6B',
systemImageName: 'xmark.circle',
},
},
paused: {
title: 'Paused',
resumeButton: {
text: 'Resume',
textColor: '#4A90D9',
systemImageName: 'play.circle',
},
},
},
tintColor: '#FF6B6B',
metadata: {
category: 'cooking',
recipe: 'pasta',
},
},
sound: 'custom-sound',
})
const id = crypto.randomUUID()
await AlarmKitManager.shared.schedule(id, config)
await AlarmKitManager.shared.countdown(id)
// Use scheduleOrReschedule for safe updates (cancels existing if present)
await AlarmKitManager.shared.scheduleOrReschedule(id, newConfig)
// Use cancelIfExists for safe cancellation (ignores ALARM_NOT_FOUND)
await AlarmKitManager.shared.cancelIfExists(id)
```
--------------------------------
### Creating Configurations with AlarmConfigurationFactory
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Provides factory methods for generating timer, recurring alarm, and combined configurations.
```typescript
import { AlarmConfigurationFactory, AlarmKitManager } from 'react-native-ios-alarmkit'
// Timer-only configuration
const timerConfig = AlarmConfigurationFactory.timer({
duration: 600, // 10 minutes
attributes: {
presentation: {
alert: {
title: 'Break Time Over',
stopButton: { text: 'OK', textColor: '#FFF', systemImageName: 'checkmark' },
},
},
tintColor: '#5B7FA6',
},
})
// Alarm-only configuration (recurring schedule)
const alarmConfig = AlarmConfigurationFactory.alarm({
schedule: {
type: 'relative',
hour: 8,
minute: 30,
weekdays: ['monday', 'wednesday', 'friday'],
},
attributes: {
presentation: {
alert: {
title: 'Workout Time',
stopButton: { text: 'Dismiss', textColor: '#FFF', systemImageName: 'xmark' },
secondaryButton: { text: 'Snooze', textColor: '#FFF', systemImageName: 'zzz' },
secondaryButtonBehavior: 'countdown',
},
},
tintColor: '#2D6A4F',
},
})
// Full configuration with both countdown and schedule
const fullConfig = AlarmConfigurationFactory.create({
countdownDuration: {
preAlert: 300, // 5 min countdown before alert
postAlert: 540, // 9 min snooze duration
},
schedule: {
type: 'relative',
hour: 7,
minute: 0,
},
attributes: {
presentation: {
alert: { title: 'Wake Up', stopButton: { text: 'Stop', textColor: '#FFF', systemImageName: 'stop' } },
countdown: { title: 'Alarm in' },
},
},
})
const id = crypto.randomUUID()
await AlarmKitManager.shared.schedule(id, fullConfig)
```
--------------------------------
### AlarmConfigurationFactory
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Factory methods to create alarm and timer configurations.
```APIDOC
## AlarmConfigurationFactory
### Methods
- **timer(options)** - Creates a timer-only configuration
- **alarm(options)** - Creates an alarm-only configuration
- **create(options)** - Creates a full configuration with both countdown and schedule
```
--------------------------------
### Listen to Alarm and Authorization Events
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Set up listeners to receive real-time updates for alarm changes and authorization status. Remember to remove listeners when they are no longer needed to prevent memory leaks.
```typescript
const alarmsSub = AlarmKit.addAlarmsListener((alarms) => {
console.log('Alarms updated:', alarms)
})
const authSub = AlarmKit.addAuthorizationListener((state) => {
console.log('Authorization changed:', state)
})
// Cleanup
alarmsSub.remove()
authSub.remove()
```
--------------------------------
### Build and Run Android App
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/example/README.md
Execute this command from the root of your React Native project to build and run the Android application. Ensure Metro is running in another terminal.
```sh
bun run android
```
--------------------------------
### Pushing a Tagged Release
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/CONTRIBUTING.md
Push the newly created Git tag to the remote repository to publish the release.
```bash
git push origin vX.Y.Z
```
--------------------------------
### iOS Info.plist Configuration
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Add the NSAlarmKitUsageDescription key to your Info.plist file to allow the app to schedule alarms. This is required for AlarmKit functionality.
```xml
NSAlarmKitUsageDescriptionThis app needs to schedule alarms to remind you at important times.
```
--------------------------------
### AlarmConfigurationFactory
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Factory methods for creating alarm configurations with proper structure, supporting timers, alarms, and combined configurations.
```APIDOC
## AlarmConfigurationFactory
Factory methods for creating alarm configurations with proper structure. Provides `timer()`, `alarm()`, and `create()` methods for different use cases.
### Timer Configuration
Creates a configuration specifically for a timer.
#### Method
POST
#### Endpoint
/api/alarms/configure/timer
#### Parameters
##### Request Body
- **duration** (number) - Required - Duration of the timer in seconds.
- **attributes** (object) - Optional - Customization for presentation, tint color, and metadata.
- **presentation** (object) - Optional - Defines alert presentation.
- **alert** (object) - Optional - Configuration for the alert.
- **title** (string) - Optional - Title of the alert.
- **stopButton** (object) - Optional - Configuration for the stop button.
- **text** (string) - Optional - Text displayed on the button.
- **textColor** (string) - Optional - Text color of the button.
- **systemImageName** (string) - Optional - System image name for the button.
- **tintColor** (string) - Optional - The tint color for the timer UI.
#### Request Example
```json
{
"duration": 600,
"attributes": {
"presentation": {
"alert": {
"title": "Break Time Over",
"stopButton": {
"text": "OK",
"textColor": "#FFF",
"systemImageName": "checkmark"
}
}
},
"tintColor": "#5B7FA6"
}
}
```
### Alarm Configuration
Creates a configuration for a scheduled alarm, potentially recurring.
#### Method
POST
#### Endpoint
/api/alarms/configure/alarm
#### Parameters
##### Request Body
- **schedule** (object) - Required - Defines the alarm schedule.
- **type** (string) - Required - Type of schedule ('relative' or 'absolute').
- **hour** (number) - Required - Hour of the day (0-23).
- **minute** (number) - Required - Minute of the hour (0-59).
- **weekdays** (array) - Optional - Array of weekdays (e.g., ['monday', 'wednesday']).
- **attributes** (object) - Optional - Customization for presentation, tint color, and metadata.
- **presentation** (object) - Optional - Defines alert presentation.
- **alert** (object) - Optional - Configuration for the alert.
- **title** (string) - Optional - Title of the alert.
- **stopButton** (object) - Optional - Configuration for the stop button.
- **text** (string) - Optional - Text displayed on the button.
- **textColor** (string) - Optional - Text color of the button.
- **systemImageName** (string) - Optional - System image name for the button.
- **secondaryButton** (object) - Optional - Configuration for a secondary button.
- **text** (string) - Optional - Text displayed on the button.
- **textColor** (string) - Optional - Text color of the button.
- **systemImageName** (string) - Optional - System image name for the button.
- **secondaryButtonBehavior** (string) - Optional - Behavior of the secondary button (e.g., 'countdown').
- **tintColor** (string) - Optional - The tint color for the alarm UI.
#### Request Example
```json
{
"schedule": {
"type": "relative",
"hour": 8,
"minute": 30,
"weekdays": ["monday", "wednesday", "friday"]
},
"attributes": {
"presentation": {
"alert": {
"title": "Workout Time",
"stopButton": {
"text": "Dismiss",
"textColor": "#FFF",
"systemImageName": "xmark"
},
"secondaryButton": {
"text": "Snooze",
"textColor": "#FFF",
"systemImageName": "zzz"
},
"secondaryButtonBehavior": "countdown"
}
},
"tintColor": "#2D6A4F"
}
}
```
### Full Configuration
Creates a comprehensive configuration with both countdown and schedule options.
#### Method
POST
#### Endpoint
/api/alarms/configure/create
#### Parameters
##### Request Body
- **countdownDuration** (object) - Optional - Defines countdown durations.
- **preAlert** (number) - Optional - Duration in seconds before the alert.
- **postAlert** (number) - Optional - Duration in seconds for snooze.
- **schedule** (object) - Optional - Defines the alarm schedule (same structure as Alarm Configuration).
- **attributes** (object) - Optional - Customization for presentation, tint color, and metadata.
- **presentation** (object) - Optional - Defines alert presentation.
- **alert** (object) - Optional - Configuration for the alert.
- **title** (string) - Optional - Title of the alert.
- **stopButton** (object) - Optional - Configuration for the stop button.
- **text** (string) - Optional - Text displayed on the button.
- **textColor** (string) - Optional - Text color of the button.
- **systemImageName** (string) - Optional - System image name for the button.
- **countdown** (object) - Optional - Configuration for the countdown state.
- **title** (string) - Optional - Title for the countdown view.
#### Request Example
```json
{
"countdownDuration": {
"preAlert": 300,
"postAlert": 540
},
"schedule": {
"type": "relative",
"hour": 7,
"minute": 0
},
"attributes": {
"presentation": {
"alert": {
"title": "Wake Up",
"stopButton": {
"text": "Stop",
"textColor": "#FFF",
"systemImageName": "stop"
}
},
"countdown": {
"title": "Alarm in"
}
}
}
}
```
```
--------------------------------
### Schedule Live Activity with Custom Metadata
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/docs/LIVE_ACTIVITY_SETUP.md
Pass custom data to a Live Activity using the AlarmKitManager. Ensure the metadata object matches the structure expected by the Swift Widget extension.
```typescript
const id = crypto.randomUUID()
await AlarmKitManager.shared.schedule(id, {
countdownDuration: {
preAlert: 600,
postAlert: 300,
},
presentation: { ... },
metadata: {
iconName: 'flame',
recipeName: 'Pizza',
},
})
```
--------------------------------
### Check AlarmKit Support
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Verify if the current device supports AlarmKit functionality.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
if (AlarmKit.isSupported) {
console.log('AlarmKit is available')
} else {
console.log('AlarmKit not supported on this device')
}
```
--------------------------------
### AlarmKitManager
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Singleton manager for interacting with native iOS alarm functionality.
```APIDOC
## AlarmKitManager.shared
### Description
Singleton instance mirroring native AlarmManager.shared for scheduling and managing alarms.
### Methods
- **schedule(id, config)** - Schedules a new alarm
- **cancel(id)** - Cancels an existing alarm
- **stop(id)** - Stops an active alarm
- **pause(id)** - Pauses an alarm
- **resume(id)** - Resumes a paused alarm
- **countdown(id, config)** - Starts a countdown
- **getAlarms()** - Retrieves all alarms
- **getAuthorizationState()** - Gets current auth status
- **requestAuthorization()** - Requests user permission
- **scheduleOrReschedule(id, config)** - Cancels existing alarm with ID then schedules new one
- **cancelIfExists(id)** - Cancels alarm, ignores ALARM_NOT_FOUND errors
### Listeners
- **addAlarmUpdatesListener(callback)** - Subscribe to alarm changes
- **addAuthorizationUpdatesListener(callback)** - Subscribe to auth changes
```
--------------------------------
### Subscribe to alarm and authorization events
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Registers listeners for real-time state changes. Remember to call remove() on the returned subscription for cleanup.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
// Subscribe to alarm updates
const alarmsSub = AlarmKit.addAlarmsListener((alarms) => {
console.log('Alarms updated:', alarms.length)
alarms.forEach(alarm => {
console.log(`${alarm.id}: ${alarm.state}`)
})
})
// Subscribe to authorization changes
const authSub = AlarmKit.addAuthorizationListener((state) => {
console.log('Authorization state changed:', state)
if (state === 'denied') {
// Handle permission revocation
}
})
// Cleanup when done
alarmsSub.remove()
authSub.remove()
```
--------------------------------
### Check AlarmKit Support and Request Authorization
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Before using AlarmKit, check if it's supported on the current device and request user authorization. Methods are silent no-ops if not supported.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
// Check support
if (!AlarmKit.isSupported) {
console.log('AlarmKit not supported')
}
// Request authorization
const authorized = await AlarmKit.requestAuthorization()
```
--------------------------------
### Handling AlarmKit Errors
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Demonstrates how to catch and inspect AlarmKitError instances for specific error codes.
```typescript
import {
AlarmKit,
AlarmKitError,
AlarmKitErrorCode,
} from 'react-native-ios-alarmkit'
try {
await AlarmKit.cancel(alarmId)
} catch (error) {
if (error instanceof AlarmKitError) {
console.log('Error code:', error.code)
console.log('Error message:', error.message)
console.log('Native error:', error.nativeError)
// Check specific error types
if (error.code === AlarmKitErrorCode.ALARM_NOT_FOUND) {
console.log('Alarm does not exist')
} else if (error.code === AlarmKitErrorCode.MAXIMUM_LIMIT_REACHED) {
console.log('Too many alarms scheduled')
}
}
}
```
--------------------------------
### Schedule Advanced Alarm Configurations
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Use AlarmConfigurationFactory to define complex timer and countdown behaviors, then schedule them using the AlarmKitManager. Ensure a Widget Extension is configured for countdown UI support.
```typescript
import {
AlarmKitManager,
AlarmConfigurationFactory,
} from 'react-native-ios-alarmkit'
const config = AlarmConfigurationFactory.timer({
duration: 300,
attributes: {
presentation: {
alert: {
title: 'Timer Done!',
stopButton: {
text: 'Stop',
textColor: '#FFFFFF',
systemImageName: 'stop.circle',
},
secondaryButton: {
text: 'Snooze',
textColor: '#FFFFFF',
systemImageName: 'zzz',
},
secondaryButtonBehavior: 'countdown',
},
countdown: {
title: 'Time Remaining',
pauseButton: {
text: 'Cancel',
textColor: '#FF6B6B',
systemImageName: 'xmark.circle',
},
},
paused: {
title: 'Paused',
resumeButton: {
text: 'Resume',
textColor: '#4A90D9',
systemImageName: 'play.circle',
},
},
},
tintColor: '#FF6B6B',
metadata: {
customKey: 'customValue',
},
},
sound: 'custom-sound',
})
const id = crypto.randomUUID()
await AlarmKitManager.shared.schedule(id, config)
await AlarmKitManager.shared.countdown(id)
const alarms = await AlarmKitManager.shared.getAlarms()
// Listeners (note: method names differ from Simple API)
const sub = AlarmKitManager.shared.addAlarmUpdatesListener((alarms) => {
console.log('Alarms updated:', alarms)
})
sub.remove()
```
--------------------------------
### Request Authorization
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Request user permission to schedule alarms, handling potential errors.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
try {
const authorized = await AlarmKit.requestAuthorization()
if (authorized) {
console.log('Permission granted - can now schedule alarms')
} else {
console.log('Permission denied by user')
}
} catch (error) {
console.error('Authorization request failed:', error)
}
```
--------------------------------
### Request Authorization
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Requests permission to schedule alarms. Returns true if authorized, false if denied. Throws AlarmKitError if the OS rejects the request.
```APIDOC
## AlarmKit.requestAuthorization()
### Description
Request permission to schedule alarms. Returns `true` if authorized, `false` if denied. Throws `AlarmKitError` if the OS rejects the request (e.g., missing `NSAlarmKitUsageDescription`).
### Usage
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
try {
const authorized = await AlarmKit.requestAuthorization()
if (authorized) {
console.log('Permission granted - can now schedule alarms')
} else {
console.log('Permission denied by user')
}
} catch (error) {
console.error('Authorization request failed:', error)
}
```
```
--------------------------------
### AlarmKit Type Definitions
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Core interfaces and types for alarm configuration, state, and presentation.
```typescript
type AuthorizationState = 'notDetermined' | 'authorized' | 'denied'
type AlarmState = 'scheduled' | 'countdown' | 'paused' | 'alerting'
type Weekday =
| 'sunday'
| 'monday'
| 'tuesday'
| 'wednesday'
| 'thursday'
| 'friday'
| 'saturday'
interface Alarm {
id: string // UUID
state: AlarmState
countdownDuration: CountdownDuration | null
schedule: AlarmSchedule | null
}
interface SimpleTimerConfig {
duration: number // seconds
title: string
snoozeEnabled?: boolean
snoozeDuration?: number // seconds, default 300
tintColor?: string // hex color
sound?: string // custom sound filename
}
interface SimpleAlarmConfig {
hour: number // 0-23
minute: number // 0-59
weekdays?: Weekday[] // omit for daily
title: string
snoozeEnabled?: boolean
snoozeDuration?: number // seconds, default 540
tintColor?: string
sound?: string
}
interface AlarmButton {
text: string
textColor: string
systemImageName: string
}
interface AlarmPresentation {
alert: AlertPresentation
countdown?: CountdownPresentation
paused?: PausedPresentation
}
interface Subscription {
remove: () => void
}
```
--------------------------------
### Schedule a Timer
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Create a countdown timer with optional snooze and custom styling.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
const timerId = crypto.randomUUID()
await AlarmKit.scheduleTimer(timerId, {
duration: 300, // 5 minutes in seconds
title: 'Timer Done!',
snoozeEnabled: true,
snoozeDuration: 60, // 1 minute snooze
tintColor: '#FF6B6B', // Custom color (hex)
sound: 'custom-sound', // Optional custom sound filename
})
console.log(`Timer ${timerId} scheduled for 5 minutes`)
```
--------------------------------
### Handling AlarmKit Errors
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Demonstrates how to catch and handle specific AlarmKitError codes for programmatic error recovery.
```typescript
import AlarmKit, { AlarmKitError, AlarmKitErrorCode } from 'react-native-ios-alarmkit'
try {
await AlarmKit.scheduleTimer(alarmId, {
duration: 300,
title: 'Timer',
})
} catch (error) {
if (error instanceof AlarmKitError) {
console.log('Error code:', error.code)
console.log('Error message:', error.message)
console.log('Native error:', error.nativeError)
switch (error.code) {
case AlarmKitErrorCode.INVALID_UUID:
console.log('Invalid alarm ID - use crypto.randomUUID()')
break
case AlarmKitErrorCode.MAXIMUM_LIMIT_REACHED:
console.log('Too many alarms - cancel some before adding more')
break
case AlarmKitErrorCode.UNAUTHORIZED:
console.log('Permission denied - request authorization first')
break
case AlarmKitErrorCode.ALARM_EXISTS:
console.log('Alarm with this ID already exists')
break
default:
console.log('Unexpected error:', error.message)
}
}
}
```
--------------------------------
### React Hooks
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/README.md
Hooks for observing alarm and authorization states in React components.
```APIDOC
## useAlarms()
### Description
Returns the current list of alarms, any errors, and the loading state.
### Response
- **alarms** (Alarm[]) - List of current alarms
- **error** (AlarmKitError | null) - Error object if an operation failed
- **isLoading** (boolean) - Loading status
## useAuthorizationState()
### Description
Returns the current authorization state for alarm permissions.
### Response
- **state** (AuthorizationState) - Current auth state ('notDetermined' | 'authorized' | 'denied')
- **error** (AlarmKitError | null) - Error object if an operation failed
- **isLoading** (boolean) - Loading status
```
--------------------------------
### CMake Build Configuration for NitroAlarmkit
Source: https://github.com/sauravhiremath/react-native-ios-alarmkit/blob/master/android/CMakeLists.txt
Defines the shared library, C++ standard, and necessary include directories for the Android build process.
```cmake
project(NitroAlarmkit)
cmake_minimum_required(VERSION 3.9.0)
set (PACKAGE_NAME NitroAlarmkit)
set (CMAKE_VERBOSE_MAKEFILE ON)
set (CMAKE_CXX_STANDARD 20)
# Define C++ library and add all sources
add_library(${PACKAGE_NAME} SHARED
src/main/cpp/cpp-adapter.cpp
)
# Add Nitrogen specs :)
include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/NitroAlarmkit+autolinking.cmake)
# Set up local includes
include_directories(
"src/main/cpp"
"../cpp"
)
find_library(LOG_LIB log)
# Link all libraries together
target_link_libraries(
${PACKAGE_NAME}
${LOG_LIB}
android # <-- Android core
)
```
--------------------------------
### Event Listeners
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Subscribe to real-time alarm and authorization state changes. Returns a subscription object with a `remove()` method for cleanup.
```APIDOC
## Event Listeners
### Description
Allows you to subscribe to real-time updates for both alarm state changes and authorization status changes. These listeners provide a way to react to events as they happen without needing to poll.
### Methods
- **`AlarmKit.addAlarmsListener(callback: (alarms: Alarm[]) => void): Subscription`**
- **`AlarmKit.addAuthorizationListener(callback: (state: string) => void): Subscription`**
### Parameters
- **callback**: A function that will be called with the updated data when an event occurs.
- For `addAlarmsListener`, the callback receives an array of `Alarm` objects.
- For `addAuthorizationListener`, the callback receives the new authorization state as a string.
### Return Value
A `Subscription` object with a `remove()` method. Call `remove()` to unsubscribe from the listener and prevent memory leaks.
### Usage
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
// Subscribe to alarm updates
const alarmsSub = AlarmKit.addAlarmsListener((alarms) => {
console.log('Alarms updated:', alarms.length)
alarms.forEach(alarm => {
console.log(`${alarm.id}: ${alarm.state}`)
})
})
// Subscribe to authorization changes
const authSub = AlarmKit.addAuthorizationListener((state) => {
console.log('Authorization state changed:', state)
if (state === 'denied') {
// Handle permission revocation
}
})
// Cleanup when done
// Call these methods in your component's cleanup function (e.g., useEffect return function)
alarmsSub.remove()
authSub.remove()
```
```
--------------------------------
### Schedule an Alarm
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Create recurring alarms for specific times or weekdays.
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
const alarmId = crypto.randomUUID()
// Schedule weekday wake-up alarm at 7:00 AM
await AlarmKit.scheduleAlarm(alarmId, {
hour: 7,
minute: 0,
weekdays: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
title: 'Wake Up!',
snoozeEnabled: true,
snoozeDuration: 540, // 9 minutes snooze (default)
tintColor: '#4A90D9',
})
// Schedule daily alarm (omit weekdays for every day)
const dailyAlarmId = crypto.randomUUID()
await AlarmKit.scheduleAlarm(dailyAlarmId, {
hour: 22,
minute: 30,
title: 'Time for bed',
snoozeEnabled: false,
})
```
--------------------------------
### AlarmKit.pause() and AlarmKit.resume()
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Pause an active countdown and resume a paused countdown. Only works when the alarm is in the appropriate state.
```APIDOC
## AlarmKit.pause() and AlarmKit.resume()
### Description
Pause an active countdown and resume a paused countdown. These functions only work when the alarm is in the appropriate state (e.g., 'countdown' for pause, 'paused' for resume).
### Method
`await` (asynchronous function)
### Endpoint
`AlarmKit.pause(timerId: string)`
`AlarmKit.resume(timerId: string)`
### Parameters
#### Path Parameters
- **timerId** (string) - Required - The unique identifier of the timer/alarm to pause or resume.
### Request Example
```typescript
import AlarmKit from 'react-native-ios-alarmkit'
// Pause a countdown
await AlarmKit.pause(timerId)
console.log('Timer paused')
// Later, resume the countdown
await AlarmKit.resume(timerId)
console.log('Timer resumed')
```
### Response
No explicit success response body. Success is indicated by the absence of an error.
```
--------------------------------
### Manage authorization with useAuthorizationState hook
Source: https://context7.com/sauravhiremath/react-native-ios-alarmkit/llms.txt
Provides reactive access to the current authorization state and handles permission requests.
```typescript
import { useAuthorizationState } from 'react-native-ios-alarmkit'
import { Linking } from 'react-native'
function AuthorizationStatus() {
const { state, isLoading, error } = useAuthorizationState()
if (isLoading) {
return Checking permissions...
}
if (error) {
return Error: {error.message}
}
const handlePress = async () => {
if (state === 'denied') {
await Linking.openSettings()
} else if (state === 'notDetermined') {
await AlarmKit.requestAuthorization()
}
}
return (
Authorization: {state}
{state !== 'authorized' && (
)}
)
}
```