任意加载= YES,并检查功能中的后台提取。我究竟做错了什么?是否有解释这些概念的在线课程?这是在app委托文件中。我想在应用程序进入后台时从URL检索数据。
func applicationDidEnterBackground(_ application: UIApplication) {
if let url = URL(string:"https://finviz.com/screener.ashx?v=111&f=exch_nasd,sh_curvol_o500,sh_price_u5&o=-change") {
//url successful
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
//failed
print("FAILED")
} else {
//successful
print("SUCCESSFUL")
}
})
print("TASK DID NOT RUN")
task.resume()
} else {
//url failed
print("URL FAILED")
}
}
答案 0 :(得分:1)
在运行代码之前使用beginBackgroundTask(expirationHandler:)
。看看here。进入后台时系统会停止执行您的应用程序,您应该使用此功能以获得更多运行时间。同时删除" TASK DID NOT RUN"。它将始终打印
这是您的完整代码:
var identifier: UIBackgroundTaskIdentifier = 0
func applicationDidEnterBackground(_ application: UIApplication) {
self.identifier = application.beginBackgroundTask {
application.endBackgroundTask(self.identifier)
}
if let url = URL(string:"https://finviz.com/screener.ashx?v=111&f=exch_nasd,sh_curvol_o500,sh_price_u5&o=-change") {
//url successful
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
//failed
print("FAILED")
} else {
//successful
print("SUCCESSFUL")
}
})
task.resume()
} else {
//url failed
print("URL FAILED")
}
}