我创建了一个简单的json应用程序并且工作正常,但是当应用程序要加载后台数据时,有人请建议我使用代码。
let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
if error != nil {
print(error?.localizedDescription ?? "")
}
if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
for jsonreviews in resultArray {
let review = Review()
review.rating = jsonreviews["rating"] as? Int ?? 0
review.text = jsonreviews["text"] as! String
review.time = jsonreviews["time"] as! String
reviews.append(review)
}
DispatchQueue.main.async {
self.tableview.reloadData() // if you use tableview
}
}
}
task.resume()
答案 0 :(得分:0)
答案 1 :(得分:0)
如果您只需要额外的几分钟来完成请求,那么简单的解决方案是请求操作系统一点时间来完成此操作。请参阅Background Execution: Executing Finite-Length Tasks。
因此,要告诉操作系统,如果在任务运行时应用程序恰好被暂停,您可能需要一点额外的时间来运行请求,您可以这样做:
var backgroundTask = UIBackgroundTaskInvalid
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "com.domain.app.data") {
// do whatever clean up you want before your app exits
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
并且,当任务完成时:
if backgroundTask != UIBackgroundTaskInvalid {
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
因此:
var backgroundTask = UIBackgroundTaskInvalid
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "com.domain.app.data") {
// do whatever clean up you want before your app exits
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { data, response, error in
guard let data = data, error != nil else {
print(error?.localizedDescription ?? "")
return
}
if let resultArray = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] {
for jsonreviews in resultArray {
let review = Review()
review.rating = jsonreviews["rating"] as? Int ?? 0
review.text = (jsonreviews["text"] as! String)
review.time = (jsonreviews["time"] as! String)
reviews.append(review)
}
DispatchQueue.main.async {
self.tableview.reloadData() // if you use tableview
}
}
if backgroundTask != UIBackgroundTaskInvalid {
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
}
task.resume()
如果您认为完成查询需要的时间超过几分钟,则可以实现后台URLSession
,尽管这可能对此方案而言过度。它需要进行一些更改,包括:
URLSession
;