我在Swift代码中有一个函数scheduleFutureLocalNotifications()
,它会创建64 UILocalNotification
,以便将来触发。
最初该函数是在viewDidLoad()
调用的,但是在启动应用程序时会导致延迟。
接下来,在活动应用程序期间调用了该函数,但这会导致不可预测的暂停或滞后用户界面。
最后,当应用程序在收到UIApplicationDidEnterBackground
通知后转换到后台时,该功能被移动以触发,但这会导致iOS在后台准备本地通知时暂时滞后。这在旧设备上显得更为明显。
问题:
1 - 如何减少延迟并提高用户界面响应能力 创建本地通知?
2 - 可以采用哪些更好的技术来安排64 通知?
3 - 有什么其他更好的时间可以调用函数
scheduleFutureLocalNotifications()
?
代码:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
scheduleFutureLocalNotifications()
}
func scheduleFutureLocalNotifications() {
// Remove all previous local notifications
let application = UIApplication.sharedApplication()
application.cancelAllLocalNotifications()
// Set new local notifications to fire over the coming 64 days
for nextLocalNotification in 1...64 {
// Add calendar day
let addDayComponent = NSDateComponents()
addDayComponent.day = nextLocalNotification
let calendar = NSCalendar.currentCalendar()
let nextDate = calendar.dateByAddingComponents(addDayComponent, toDate: NSDate(), options: [])
// Set day components for next fire date
let nextLocalNotificationDate = NSCalendar.currentCalendar()
let components = nextLocalNotificationDate.components([.Year, .Month, .Day], fromDate: nextDate!)
let year = components.year
let month = components.month
let day = components.day
// Set notification fire date
let componentsFireDate = NSDateComponents()
componentsFireDate.year = year
componentsFireDate.month = month
componentsFireDate.day = day
componentsFireDate.hour = 0
componentsFireDate.minute = 0
componentsFireDate.second = 5
let fireDateLocalNotification = calendar.dateFromComponents(componentsFireDate)!
// Schedule local notification
let localNotification = UILocalNotification()
localNotification.fireDate = fireDateLocalNotification
localNotification.alertBody = ""
localNotification.alertAction = ""
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.repeatInterval = NSCalendarUnit(rawValue: 0)
localNotification.applicationIconBadgeNumber = nextLocalNotification
application.scheduleLocalNotification(localNotification)
}
}
}
答案 0 :(得分:1)
您可以异步地将该函数调度到另一个队列。这将确保主队列不会被阻止执行调度,并将阻止UI无响应:
override func viewDidLoad() {
super.viewDidLoad()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
scheduleFutureLocalNotifications()
}
}