iOS 시계앱에서 알람, 타이머를 설정한후 설정 시간에 도달하면
앱이 background 상태일때 화면 상단에 푸시 메시지가 표시된다.
1. 프레임워크 임포트
import UserNotifications
* 나는 Xcode 13.4.1 사용중인데 UserNotifications가 아마 UIKit에 포함되어 있는 듯 하다. 그래서
UIkit을 import한 상태라면 UserNotifications를 import하지 않아도 된다.
2. 권한 요청하기
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{
// 사용자에게 노티피케이션 받을지 물어보기(앱 첫 시작시 요청화면이 한번만 화면에 노출된다)
askUserNotifAuthorization()
return true
}
func askUserNotification()
{
if #available(iOS 10.0, *)
{
let notifCenter = UNUserNotificationCenter.current()
notifCenter.requestAuthorization(options: [.alert, .badge, .sound]){(didAllow, e) in }
}
}
앱 델리게이트의 application(_:didFinishLaunchingWithOptions:) 메서드 내에서 권한 요청을 한다.
UserNotification은 iOS10이후부터 지원하므로 #available 문을 삽입한다.
requestAuthorization()함수를 호출하면 사용자에게 권한을 요청하는 화면을 앱 첫 시작시 표시한다.
사용자가 버튼을 누르면 시스템은 사용자의 응답을 저장해 놓으므로 이후부터는 이 창이 표시되지 않는다.
위에서 옵션에 alert, badge, sound를 지정했는데 원하는 것만 지정해 주면 된다.
3. notification 보내기
func sceneWillResignActive(_ scene: UIScene)
{
UNUserNotificationCenter.current().getNotificationSettings(){ settings in
if settings.authorizationStatus == UNAuthorizationStatus.authorized
{
let contents = UNMutableNotificationContent()
contents.title = "알림"
contents.body = "알림이 도착했습니다."
// 기본 사운드
// contents.sound = UNNotificationSound.default
contents.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "bell.wav"))
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let request = UNNotificationRequest(identifier: "my notifcation", content: contents, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
}
}
1. UNMutableNotificationContent객체를 만들어 표시할 title, body, sound를 설정
2. UNTimeIntervalNotificationTrigger 함수로 몇초후에 알림을 보낼지와 반복 유무를 설정
3. UNNotificationRequest 함수로 requst 객체 생성
4. UNUserNotificationCenter.current().add 함수로 센터에 추가
이렇게 하면 설정한 시간 후에 로컬 푸시가 화면 상단에 표시된다.
* 그외 사용자가 알림을 터치한 이후의 처리를 위해 델리게이트 함수도 구현해줄수 있다.
'iOS Solution' 카테고리의 다른 글
화면을 세로모드로 제한하기, portrait 세로모드만 지원하기 (0) | 2022.09.01 |
---|---|
텍스트 필드에 숫자만 입력하도록 제한하기, UITextField number only (0) | 2022.08.30 |
커스텀 폰트 추가하기 (0) | 2022.08.19 |
UserDefault에 저장한 데이터가 바로 업데이트 되지 않는다 (0) | 2022.08.12 |
오토레이아웃 이용시 뷰의 frame 값 얻기 (0) | 2022.08.09 |