티스토리 뷰

반응형

앱 개발하다보면 알람 기능이 필요할 경우가 많습니다. 제가 구현한 기능은 "시간 설정" 을 통한 "Notification" 호출 입니다. 스위프트에서는 Local Notification 제공하고 있습니다.


FCM을 구현하다보면 인증서를 등록해야하지만, 로컬에서 알림을 알려주기에 생략 가능합니다.


1. 알림 기능 사용 유무 표시 및 델리게이트 등록 (AppDelegate.swift)

Application에 Notification(알림) 기능을 사용할지 사용자에게 알려주는 기능을 넣습니다. 그리고 델리게이트도 같이 넣습니다.

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {   
 
     
 
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound], completionHandler: { (authorized, error) in
 
        if !authorized {
 
               print("App is useless becase you did not allow notification")
 
        }
 
    })
 
       
 
    let HollowAction = UNNotificationAction(identifier: "addHellow", title: "Hellow", options: [])
 
    let ByeAction = UNNotificationAction(identifier: "addBye", title: "Bye", options: [])
 
    let category = UNNotificationCategory(identifier: "eduCategory", actions: [HollowAction, ByeAction], intentIdentifiers: [], options: [])
 
 
 
    UNUserNotificationCenter.current().setNotificationCategories([category])
 
    UNUserNotificationCenter.current().delegate = self        
 
 
 
    return true
 
}


 

2. 델리게이트 오버라이딩  (AppDelegate.swift)

userNotificationCenter( _ , response, completionHandler)  은 Notify 후 카테고리 선택 시 해당 부분을 호출하게 됩니다.

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//UNUserNotificationCenterDelegate
 
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
 
    if response.actionIdentifier == "addHellow" {
 
       print("Say Hellow!")
 
    }else{
 
       print("Say Bye~")
 
    }
 
}


 

3. 알림창 구현 (AppDelegate.swift)

trigger을 이용한 알림을 구현하였습니다. 주석으로 시간 기준, 일자 기준, 일주일 기준으로 알림을 설정할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
func showEduNotification(date: Date){
 
    let content = UNMutableNotificationContent()
 
    content.title = "Say Hello"
 
    content.body = "Jusy a remind Me"
 
    content.sound = UNNotificationSound.default()
 
    content.categoryIdentifier = "eduCategory"
 
      
 
      //Timmer
 
      // let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false)
 
       
 
      //Date
 
      // let date = Date(timeIntervalSinceNow: 3600)
 
      // let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: date)
 
      // let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,repeats: false)
 
 
 
    //Weekly
 
      //  let triggerWeekly = Calendar.current.dateComponents([.weekday,hour,.minute,.second,], from: date)
 
      //  let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
 
 
 
      //Daily
 
      let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
 
      let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)       
 
      let request = UNNotificationRequest(identifier: "eduNotification", content: content, trigger: trigger)
 
 
 
      UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
 
      UNUserNotificationCenter.current().add(request){ (error) in
 
        if let error = error {
 
             print("Error:\(error.localizedDescription)")
 
          }
 
   }
 
}




4. DatePicker을 이용한 알림창 호출 (ViewController.swift)

trigger을 이용한 알림을 구현하였습니다. 주석으로 시간 기준, 일자 기준, 일주일 기준으로 알림을 설정할 수 있습니다.

    

1
2
3
4
5
6
7
8
9
10
11
12
13
var appDelegate = UIApplication.shared.delegate as? AppDelegate
 
 
 
@IBOutlet var timmerPicker: UIDatePicker!
 
@IBAction func showNotificationAction(_ sender: Any) {
 
   print("date= \(timmerPicker.date)")
 
   appDelegate?.showEduNotification(date: timmerPicker.date)
 
}




자세한 구현 소스는 여기에서 확인해주세요.


참고


반응형
댓글