我有一個函數scheduleFutureLocalNotifications()
在Swift代碼中創建64 UILocalNotification
將在未來觸發。調度導致滯後和延遲用戶界面的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)
}
}
}
通過在'dispatch_async' – Paulw11
包裹調用'scheduleFutureLocalNotifications'分派代碼到後臺線程謝謝@ Paulw11你能解釋一下嗎?你是否打算做以下事情? dispatch_get_global_queue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0),{() - > void self.scheduleFutureLocalNotifications()}) – user4806509
你能解釋一下更多關於到底是什麼嗎? – user4806509