【问题标题】:Can I use Firebase actions in the background of an app (while the app is closed), iOS, Swift我可以在应用程序(应用程序关闭时)、iOS、Swift 的后台使用 Firebase 操作吗
【发布时间】:2019-08-28 10:26:37
【问题描述】:
我想将一张图片和一些数据上传到 Firebase 存储和 Firebase Firestore。我的所有代码都在工作,但是当我离开应用程序时,上传停止。有没有办法让任务在后台运行?
我知道 URLSession 可以,但我不知道如何使用 Firebase。
总结:
我想在 Swift 的后台(应用关闭时)将数据上传到 Firebase。
提前致谢!
【问题讨论】:
标签:
ios
swift
firebase
background-task
【解决方案1】:
这段代码似乎有效:
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