我想将图像和一些数据上传到Firebase Storage和Firebase Firestore。我已经完成所有代码,但是当我离开应用程序时,上传停止。有什么办法可以使任务在后台运行?
我知道URLSession可以实现,但是我不知道如何使用Firebase做到这一点。
摘要:
我想在Swift中在后台(关闭应用程序时)将数据上传到Firebase。
谢谢!
答案 0 :(得分:0)
此代码似乎有效:
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