我想将图像和一些数据上传到 Firebase Storage 和 Firebase Firestore。我的所有代码都可以运行,但是当我离开应用程序时,上传就会停止。有什么可能的方法让任务在后台运行吗?
我知道可以使用 URLSession,但我不知道如何使用 Firebase 来实现。
摘要:
我想在 Swift 中在后台(当应用关闭时)将数据上传到 Firebase。
提前致谢!
最佳答案
这段代码似乎有效:
class PhotoUploadManager {
static var urlSessionIdentifier = "photoUploadsFromMainApp" // Should be changed in app extensions.
static let urlSession: URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: PhotoUploadManager.urlSessionIdentifier)
configuration.sessionSendsLaunchEvents = false
configuration.sharedContainerIdentifier = "my-suite-name"
return URLSession(configuration: configuration)
}()
// ...
// Example upload URL: https://firebasestorage.googleapis.com/v0/b/my-bucket-name/o?name=user-photos/someUserId/ios/photoKey.jpg
func startUpload(fileUrl: URL, contentType: String, uploadUrl: URL) {
Auth.auth().currentUser?.getIDToken() { token, error in
if let error = error {
print("ID token retrieval error: \(error.localizedDescription)")
return
}
guard let token = token else {
print("No token.")
return
}
var urlRequest = URLRequest(url: uploadUrl)
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
let uploadTask = PhotoUploadManager.urlSession.uploadTask(with: urlRequest, fromFile: fileUrl)
uploadTask.resume()
}
}
}
感谢@Gagan_iOS! 来源: https://github.com/firebase/firebase-ios-sdk/issues/147
关于ios - 我可以在应用程序(应用程序关闭时)、iOS、Swift 的后台使用 Firebase 操作吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55553645/