首页 > 解决方案 > 在特定时间重复本地通知,并在同一时间间隔后重复

问题描述

它可能与问题重复 -每天在设定的时间使用 swift 重复本地通知 但 UILocalNotifications 已弃用 iOS 10

我正在开发警报应用程序,我需要两件事 1. 一次本地通知 2. 间隔一段时间后重复

/// Code used to set notification
let content = UNMutableNotificationContent()
            content.body = NSString.localizedUserNotificationString(forKey: titleOfNotification, arguments: nil)
content.userInfo=[]

工作正常的代码在准确的时间点击通知

/* ---> Working Fine --> how i can repeat this after 60 second if untouched
   let triggerDaily = Calendar.current.dateComponents([.hour,.minute,], from: dates)
   let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: weekdays.isEmpty == true ? false : true)
*/


/// ---> Making it Repeat After Time - How Time is passed here ?
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)

/// ---> Adding Request
let request = UNNotificationRequest(identifier:dateOfNotification, content: content, trigger: trigger)                   UNUserNotificationCenter.current().add(request){(error) in
                        if (error != nil){
                            print(error?.localizedDescription ?? "Nahi pta")
                        } else {
                            semaphore.signal()
                            print("Successfully Done")
                        }
                    }

我怎样才能同时实现这两件事?

标签: swiftuilocalnotificationunnotificationrequest

解决方案


您可以使用 UNUserNotificationCenter 进行本地通知,同时,对于重复通知,您可以使用 performFetchWithCompletionHandler 方法,对于此方法,您必须设置调用方法的最小时间间隔。

请点击链接了解更多详情 - https://developer.apple.com/documentation/uikit/core_app/managing_your_app_s_life_cycle/preparing_your_app_to_run_in_the_background/updating_your_app_with_background_app_refresh

还示例代码 -

 func scheduleLocalNotification(subtitle: String, description: String, offerID: String) {
    // Create Notification Content
    let notificationContent = UNMutableNotificationContent()

    // Configure Notification Content
    notificationContent.title = "New lead for " + subtitle
    notificationContent.body = description
    notificationContent.userInfo = ["aps":
        ["alert": [
            "title":  subtitle,
            "body": description,
            "content-available": "1"
            ],
         "ofrid": offerID,
         "type": "BLBGSync",
         "landinguri": "abc.com",
        ]
    ]



    // Create Notification Request

    let triggertime = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: false)

    let notificationRequest = UNNotificationRequest(identifier: "YOUR_IDENTIFIER", content: notificationContent, trigger: triggertime)


    // Add Request to User Notification Center
    UNUserNotificationCenter.current().add(notificationRequest) { (error) in
        if let error = error {
            print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
        }
    }
}

推荐阅读