[swift] Swift에서 로컬 알림을 특정 시간 간격마다 계속해서 발생하도록 설정하는 방법

이번 포스트에서는 Swift에서 iOS 디바이스에 로컬 알림을 설정하여 특정 시간 간격마다 반복해서 알림을 받는 방법에 대해 알아보겠습니다.

준비물

알림 권한 설정

먼저, 앱이 로컬 알림을 보낼 수 있도록 허용되어야 합니다. Info.plist 파일에 다음과 같은 코드를 추가하여 앱에 필요한 권한을 설정합니다.

<key>UIUserNotificationSettings</key>
<array>
    <dict>
        <key>UIUserNotificationTypeKey</key>
        <integer>(알림 설정 타입)</integer>
        <key>UIUserNotificationActionSettingsKey</key>
        <array>
            <dict>
                <key>UIUserNotificationActionTitleKey</key>
                <string>(액션 제목)</string>
                <key>UIUserNotificationActionIdentifierKey</key>
                <string>(액션 식별자)</string>
                <key>UIUserNotificationActivationModeKey</key>
                <string>UIUserNotificationActivationModeForeground</string>
                <key>UIUserNotificationActionContextKey</key>
                <integer>0</integer>
            </dict>
        </array>
    </dict>
</array>

로컬 알림 설정

로컬 알림을 설정하기 위해 아래의 단계를 따르세요.

  1. UNUserNotificationCenter 객체를 생성합니다.
    let center = UNUserNotificationCenter.current()
    
  2. 알림 설정을 요청합니다.
    center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
     // 알림 권한 요청 결과 처리
    }
    
  3. 알림 소리 등의 기본 설정을 정의합니다.
    let sound = UNNotificationSound.default
    let content = UNMutableNotificationContent()
    content.sound = sound
    
  4. 반복 알림을 설정합니다.
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (알림 간격), repeats: true)
    
  5. 알림 요청을 생성합니다.
    let request = UNNotificationRequest(identifier: (알림 식별자), content: content, trigger: trigger)
    
  6. 알림을 등록합니다.
    center.add(request) { (error) in
     // 알림 등록 결과 처리
    }
    

위의 단계를 순서대로 따르면 로컬 알림을 특정 시간 간격마다 계속해서 발생하도록 설정할 수 있습니다.

결론

이번 포스트에서는 Swift에서 로컬 알림을 특정 시간 간격마다 계속해서 발생하도록 설정하는 방법에 대해 알아보았습니다. 자세한 내용은 Apple 공식 문서를 참조하시기 바랍니다.