我正在从 Firebase 存储中下载图像,如下所示:
let storage = FIRStorage.storage()
// Create a storage reference from our storage service
let storageRef = storage.reference(forURL: "MY_STORAGE_URL")
let imageRef = storageRef.child("Path_to_image")
// Download image in memory
let downloadTask = imageRef.data(withMaxSize: 1 * 1024 * 1024) {
(data, error) -> Void in
if (error != nil) {
//Handle the error
} else {
guard let imageData = data else {
print("Unable to unwrap image data.")
return
}
let downloadedImage = UIImage(data: imageData)
//Do some stuff with the image
}
}
我还使用以下观察器监视下载过程中发生的情况:
// Observe changes in status
downloadTask.observe(.resume) { (snapshot) -> Void in
// Download resumed, also fires when the download starts
}
downloadTask.observe(.pause) { (snapshot) -> Void in
// Download paused
}
downloadTask.observe(.progress) { (snapshot) -> Void in
// Download reported progress
}
downloadTask.observe(.success) { (snapshot) -> Void in
// Download completed successfully
}
downloadTask.observe(.failure) { (snapshot) -> Void in
//Download failed
}
当应用程序首次启动时,一切正常。但是,如果该应用程序进入后台并且我尝试使用其他一些应用程序(Facebook、Twitter 等),然后将应用程序带回前台,我就会遇到问题。如果我让应用程序在前台打开并运行超过或等于 1 小时,我也会遇到问题。
问题是 let downloadTask = imageRef.data(withMaxSize:
blah blah blah(在上面的第一个代码块中)中的完成处理程序永远不会被调用。如果完成处理程序从未被调用,我永远无法打开数据并尝试在我的应用程序中使用图像。
此外,在 downloadTask
观察器中,唯一被触发的完成处理程序是 .resume
和 .progress
。 .success
或 .failure
事件永远不会被触发。这对我来说似乎是一个 Firebase 存储错误,但我不确定。还有其他人遇到过类似的问题吗?我不明白为什么代码在新启动时可以正常工作,但在前台运行一段时间后或在后台运行一段时间后,图像下载停止工作。提前感谢您的任何意见。
最佳答案
不幸的是,这是目前预期的行为。 Firebase Storage(目前)仅在前台:如果应用程序在后台,我们没有持久化上传 URL,无法在后台上传,也无法在退出后台后重新启动它,所以它可能被杀死操作系统和项目未上传。
这是我们想要解决的下一件大事™(our Android SDK makes it possible,虽然并不容易),但不幸的是,目前我们还没有在这方面取得更多进展。
顺便说一下,事件更改后您的观察者将不存在——downloadTask
一旦应用程序进入后台就消失了,所以当它回到前台时,我们基本上需要一个方法来检索当前后台的所有任务,并允许您将观察者 Hook 。像这样的东西:
FIRStorage.storage().backgroundedTasks { (tasks) -> Void in
// tasks is an array of upload and download tasks
// not sure if it needs to be async
}
关于ios - 应用程序在后台运行一段时间后,Firebase 存储下载任务未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40416541/