iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 19
0
Mobile Development

從零開始-30日練習開發iOS APP系列 第 19

從零開始-30日練習開發iOS APP-IOS 13.6 鬧鐘App復刻 (二) Day-19

前言:
頁面功能差不多都完成之後,可以使用推播通知來提醒時間

正文:
以下採用設定時間來推播

func notification() {
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
        for result in orders {
            if result.SwitchOrder {
                let content = UNMutableNotificationContent()

                content.title = "鬧鐘提醒"
                content.subtitle = "現在時刻"
                content.body = "\(result.TimeOrder)"
                //content.badge = 1
                content.sound = UNNotificationSound.default
                
                let date = Date()
                let calendar = Calendar.current

                var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second],
                    from: date)
                components.year = Calendar.current.component(.year, from: Date())
                components.month = Calendar.current.component(.month, from: Date())
                components.day = Calendar.current.component(.day, from: Date())
                var subString = (result.TimeOrder as NSString).substring(with: NSMakeRange(0,2))
                components.hour = Int(subString)
                subString = (result.TimeOrder as NSString).substring(with: NSMakeRange(3,2))
                components.minute = Int(subString)
                components.second = 0
                
                let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

                let request = UNNotificationRequest(identifier: result.id , content: content, trigger: trigger)
                print(date)
                print(components)
                print("=================================================")
                UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
                    print("成功建立通知...")
                })
            }
        }
    }

成果圖:


上一篇
從零開始-30日練習開發iOS APP-IOS 13.6 鬧鐘App復刻 (一) Day-18
下一篇
從零開始-30日練習開發iOS APP-本地推播 Day-20
系列文
從零開始-30日練習開發iOS APP30

尚未有邦友留言

立即登入留言