我已经设置了后台获取,并且通过调试->模拟后台获取可以很好地工作。但是,当涉及到真实设备时,永远都不会被调用!!!我已经等了将近一个星期了,但是没有什么新鲜!
这是我的代码和设置 首先:我已从“功能”选项卡中打开了后台获取功能,并在info.plist
中检查了它的反映<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
</array>
第二:我在AppDelegate.swift中将UIApplicationBackgroundFetchIntervalMinimum设置为Minimum
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerForNotifications()
UNUserNotificationCenter.current().delegate = self
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
return true
}
第三:当我在performFetchWithCompletionHandler中调用后台获取时,我正在运行要处理的过程
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let content = UserNotifications.UNMutableNotificationContent()
let documentsPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let destinationSqliteURL = documentsPath.appendingPathComponent("MyDB.db")
let db = FMDatabase(path: destinationSqliteURL.path)
if !db.open() {
print("Unable to open database")
completionHandler(UIBackgroundFetchResult.failed)
return
}
var title : String!
if let rs = db.executeQuery("select _Title from Questions ORDER BY RANDOM() LIMIT 1;", withArgumentsIn: []){
while (rs.next()){
title = rs.string(forColumn: "_Title")
}
} else {
print("select failed: \(db.lastErrorMessage())")
completionHandler(UIBackgroundFetchResult.failed)
}
content.title = "Q&A of the Day"
content.body = title!
content.sound = UNNotificationSound.default()
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 8 // 8:00 hours
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllPendingNotificationRequests()
notificationCenter.add(request) { (error) in
if error != nil {
print("ERROR in setting up the scheduled notification request")
completionHandler(UIBackgroundFetchResult.failed)
}
else{
print("Notification is Sent")
completionHandler(UIBackgroundFetchResult.newData)
}
}
}
这在从模拟后台提取中对其进行调试时完美地起作用,但是,即使在真实设备上对其进行测试时也不会被调用。我知道,既然它甚至被调用过一次,那么我应该每天早晨8:00发送一个通知,而在实际设备上则不是这种情况。