问题描述
我遇到的问题是在BGAppRefresh调用期间无法调用URLSession请求
我启用了后台获取功能,并在info.plist中添加了必要的键
背景获取操作被完美调用,但是,当它通过完成处理程序到达URLSession时,它将失败。
这是AppDelegate代码:
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let register = BGTaskScheduler.shared.register(forTaskWithIdentifier: "ist.notification",using: nil) { task in
self.handleDailyNotifications(task: task as! BGAppRefreshTask)
}
}
func scheduleDailyNotificationRandomQASelection() {
let request = BGAppRefreshTaskRequest(identifier: "ist.notification")
request.earliestBeginDate = Date(timeIntervalSinceNow: 1*60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule Daily Notification's DB Fetcher Method: \(error)")
}
}
@available(iOS 13.0,*)
private func handleDailyNotifications(task: BGAppRefreshTask) {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.addOperation {
self.setNotifications()
}
task.expirationHandler = {
queue.cancelAllOperations()
}
let lastOperation = queue.operations.last
lastOperation?.completionBlock = {
task.setTaskCompleted(success: !(lastOperation?.isCancelled ?? false))
}
scheduleDailyNotificationRandomQASelection()
}
func setNotifications() {
let TimesURL = "xxx.com"
if let url = URL(string: TimesURL!) {
let task = URLSession.shared.dataTask(with: url) { (data,response,error) in
guard error == nil else {
print(error!)
return
}
if let data = data {
do {
//Json Parsing method//
}catch let error {
print("TimesURL Error:"+error.localizedDescription)
}
}
}
}
task.resume()
}
方法卡住了
let task = URLSession.shared.dataTask(with: url) { (data,error) in
请协助
非常感谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)