【发布时间】:2017-08-11 16:56:16
【问题描述】:
我正在开发一个应用程序,我需要每天更新我的应用程序中的数据。我决定使用后台获取。我正在从 API 下载数据,所以我使用的是 URLSession。由于performFetchWithCompletionHandler 中不允许使用完成处理程序,因此我为此目的使用委托。但我的问题是,当我的应用程序未运行时尝试更新数据时,不会调用函数didRecieve data。我是在做错什么,还是应该每天使用其他东西从 API 更新我的数据?
我的代码如下:
func createTask(url: String, id: String){
let accessKey = UserDataService().getCurrentUser().accessToken
let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: id + UUID().uuidString)
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
var request = URLRequest(url: URL(string: url)!)
request.setValue("Bearer \(accessKey!)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
let task = backgroundSession.dataTask(with: request)
task.resume()
print("task resumed")
}
这个函数在performFetchWithCompletionHandler内部被调用并创建新的dataTask,但didRecieve data没有被调用。
我也尝试在 performFetchWithCompletionHandler 中添加此代码
print("BG FETCH")
let url = "secret url"
var request = URLRequest(url: URL(string: url)!)
request.setValue("SOME KEY", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
print("DATA",data)
completionHandler(.newData)
}).resume()
感谢您的任何建议!
【问题讨论】:
-
我不确定,但非常怀疑您是否可以从 backgroundState 启动 backgroundSession。如果它已经在前台启动,您应该只能继续它。想象一下,如果应用程序能够进行长时间的后台下载并且用户永远不知道并且意识到 5Gb 是使用他的蜂窝数据下载的,将会发生什么。他们会立即删除您的应用!
-
@Honey 那你有什么建议。我的应用依赖于更新。
-
我没怎么用过后台应用刷新,但是看了下,没有看到任何提及:“performFetchWithCompletionHandler 中不允许完成处理程序”
-
@Honey 由this 和邓肯的回答确认
-
@Honey 我正在使用背景会话。无论如何,您是否建议任何其他方式来更新我的应用程序中的数据以在用户打开应用程序时准备好?
标签: ios swift nsurlsession background-fetch urlsession