swift2 在一天中的特定时间安排本地通知

4sup72z8  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(204)

我想为我的应用程序设置一个每日通知系统。它应该每天通知用户两次,一次在上午8:00(嘿,你的早晨剂量设置好了。想看看吗?),一次在下午7:00(Ssup!你的晚上剂量在里面等着)。我知道这样做,我会在一个月内用完通知,因为有64个通知上限(本地通知),但到那时,应用程序将是活的,我会完成设置远程通知更新。
我看过这个问题:How to schedule a same local notification in swift和.Day都很好,我只需要知道如何在那些指定的时间一天做两次;提前感谢!

**EDIT:**如何设置通知的具体时间是问题的一部分。NSDate API给我的时间间隔很奇怪(sinceNow/since 1973)。我只想将其设置为在晚上7点触发。:-/似乎不能用这些NSDate API来做这件事,除非我遗漏了什么。

sczxawaw

sczxawaw1#

针对Swift 4.2的更新

import UserNotifications

在AppDelegate中确认UNUserNotificationCenterDelegate,在didFinishLaunchingWithOptions中确认

let center = UNUserNotificationCenter.current()
            center.delegate = self;
            center.requestAuthorization(options: [UNAuthorizationOptions.alert, .badge, .sound]) { (granted, error) in
                if !granted {
                    print("Permission Declined");
                }
            }

let content = UNMutableNotificationContent();
            content.title = "HI";
            content.body = "Your notification is here";
            content.sound = UNNotificationSound.default;

            let gregorian = Calendar(identifier: Calendar.Identifier.gregorian);
            let now = Date();
            var components = gregorian.dateComponents(in: .autoupdatingCurrent, from: now)

            let hours = [8,19];

            for hour in hours {
                components.timeZone = TimeZone.current
                components.hour = hour;
                components.minute = 00;
                components.second = 00;

                let date = gregorian.date(from: components);
                let formatter = DateFormatter();
                formatter.dateFormat = "MM-dd-yyyy HH:mm";

                guard let dates = date else {
                    return;
                }
                var fireDate: String? 
                fireDate = formatter.string(from: dates);
                print("\(fireDate ?? "")"); // Just to Check

                let dailyTrigger = Calendar.current.dateComponents([.hour, .minute, .second], from: dates);
                let trigger = UNCalendarNotificationTrigger.init(dateMatching: dailyTrigger, repeats: true);

                let identifier = "Local Notification"
                let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

                center.add(request) { (error) in
                    if let error = error {
                        print("Error \(error.localizedDescription)")
                    }
                }
            }
xhv8bpkk

xhv8bpkk2#

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    let settings = UIUserNotificationSettings(forTypes: .Badge, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    let localNotification1 = UILocalNotification()
    localNotification1.alertBody = "Your alert message 111"
    localNotification1.timeZone = NSTimeZone.defaultTimeZone()
    localNotification1.fireDate = self.getEightAMDate()
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification1)

    let localNotification2 = UILocalNotification()
    localNotification2.alertBody = "Your alert message22"
    localNotification2.timeZone = NSTimeZone.defaultTimeZone()
    localNotification2.fireDate = self.getSevenPMDate()
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification2)
    return true
}

func getEightAMDate() -> NSDate? {
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let now: NSDate! = NSDate()

    let date10h = calendar.dateBySettingHour(8, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
    return date10h
}

func getSevenPMDate() -> NSDate? {
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let now: NSDate! = NSDate()

    let date19h = calendar.dateBySettingHour(19, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
    return date19h
}

相关问题