framework/ReactNative

갓난애기도 배울 수 있는 React Native 가이드 ⏺️ 보너스편9 – 커스텀 반복 알림 구현하기 (사용자가 주기 설정)

octo54 2025. 5. 12. 09:57
반응형

갓난애기도 배울 수 있는 React Native 가이드 ⏺️ 보너스편9 – 커스텀 반복 알림 구현하기 (사용자가 주기 설정)

지금까지 우리는 매일, 매주 반복 알림을 고정적으로 설정했습니다.
하지만 앱 사용자들은 자신이 원하는 주기를 설정하고 싶어합니다.
이번 글에서는 사용자가 직접 반복 주기를 설정할 수 있는 커스텀 반복 알림을 구현해보겠습니다. 🗓️🔔


✅ 1. 커스텀 반복 알림이 필요한 이유

  • 다양한 알림 주기: 매일, 매주뿐만 아니라 매월, 특정 요일
  • 사용자 자유도 증가: 앱 사용자가 직접 설정할 수 있는 유연한 구조
  • 알림 관리 용이: 반복 주기별로 알림을 쉽게 구분

✅ 2. 반복 주기 설정 옵션

옵션 설명

매일 매일 같은 시간에 알림
매주 특정 요일에 반복
매월 매달 같은 날짜에 알림
사용자 지정 원하는 간격으로 반복

✅ 3. 알림 설정 화면 UI 만들기

📄 RepeatAlarmScreen.js

import React, { useState } from 'react';
import { View, Text, TextInput, Button, Picker, StyleSheet } from 'react-native';
import { scheduleRepeatingNotification } from '../services/NotificationService';

export default function RepeatAlarmScreen({ navigation }) {
  const [title, setTitle] = useState('');
  const [repeatType, setRepeatType] = useState('day');

  const handleSchedule = () => {
    scheduleRepeatingNotification(title, `${repeatType} 반복 알림입니다.`, repeatType);
    navigation.goBack();
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>반복 알림 설정</Text>
      <TextInput
        placeholder="알림 제목"
        value={title}
        onChangeText={setTitle}
        style={styles.input}
      />
      <Text style={styles.label}>반복 주기 선택:</Text>
      <Picker
        selectedValue={repeatType}
        onValueChange={(itemValue) => setRepeatType(itemValue)}
        style={styles.picker}
      >
        <Picker.Item label="매일" value="day" />
        <Picker.Item label="매주" value="week" />
        <Picker.Item label="매월" value="month" />
        <Picker.Item label="사용자 지정 (분)" value="minute" />
      </Picker>
      <Button title="알림 설정" onPress={handleSchedule} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, justifyContent: 'center' },
  title: { fontSize: 24, marginBottom: 20 },
  input: { borderWidth: 1, marginBottom: 10, padding: 8, borderRadius: 5 },
  label: { fontSize: 18, marginBottom: 8 },
  picker: { height: 50, marginBottom: 20 },
});

✅ 4. NotificationService.js 수정

반응형
import PushNotification from 'react-native-push-notification';

// 반복 알림 설정
export const scheduleRepeatingNotification = (title, message, repeatType) => {
  PushNotification.localNotificationSchedule({
    channelId: "default-channel-id",
    title: title,
    message: message,
    date: new Date(Date.now() + 10 * 1000), // 10초 후 시작
    repeatType: repeatType, // day, week, month, minute
    allowWhileIdle: true,
  });
};

// 채널 생성
export const createNotificationChannel = () => {
  PushNotification.createChannel(
    {
      channelId: "default-channel-id",
      channelName: "Default Channel",
    },
    (created) => console.log(`채널 생성: ${created}`)
  );
};

✅ 5. App.js 수정

import React, { useEffect } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { Button, View, StyleSheet } from 'react-native';
import { createNotificationChannel } from './services/NotificationService';
import RepeatAlarmScreen from './screens/RepeatAlarmScreen';

const Stack = createNativeStackNavigator();

export default function App() {
  useEffect(() => {
    createNotificationChannel();
  }, []);

  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} options={{ title: '커스텀 알림 관리' }} />
        <Stack.Screen name="RepeatAlarm" component={RepeatAlarmScreen} options={{ title: '알림 설정' }} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const HomeScreen = ({ navigation }) => (
  <View style={styles.container}>
    <Button title="반복 알림 설정" onPress={() => navigation.navigate('RepeatAlarm')} />
  </View>
);

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
});

✅ 6. 실행 화면

  1. 앱 실행 → 반복 알림 설정 화면 이동
  2. 알림 제목 입력 → 반복 주기 선택 (매일, 매주, 매월, 분)
  3. "알림 설정" 버튼 클릭
  4. 선택한 주기에 맞게 알림 도착 확인

✅ 7. 사용자가 원하는 주기 설정하기

주기 선택 설정 값

매일 day
매주 week
매월 month
매분 minute

repeatType을 변경하여 주기를 설정할 수 있습니다.


✅ 8. 반복 알림 취소 기능 추가

📄 NotificationService.js

// 모든 반복 알림 취소
export const cancelAllAlarms = () => {
  PushNotification.cancelAllLocalNotifications();
};

📄 App.js

<Button title="모든 알림 취소" onPress={cancelAllAlarms} />

✅ 9. 이번 글에서 배운 것

  • 사용자가 직접 반복 주기를 설정하는 방법
  • Picker를 이용한 주기 선택 UI 구현
  • react-native-push-notification을 이용한 반복 알림 등록
  • 반복 알림 취소 방법

📘 다음 확장 예고

앱 종료 시에도 반복 알림 유지 (Headless Task)
Firebase와 연동하여 클라우드 기반 반복 알림 관리
반복 알림을 데이터베이스에 저장하여 관리


 

React Native 커스텀 반복 알림,React Native 반복 주기 설정,React Native 알림 주기 변경,React Native Push Notification 커스텀,React Native 알림 설정 화면,React Native Picker 사용법,React Native 알림 관리,React Native 주기적 알림,React Native 사용자 설정 알림,React Native FCM 반복 알림