ios - 我可以在应用程序(应用程序关闭时)、iOS、Swift 的后台使用 Firebase 操作吗

标签 ios swift firebase background-task

我想将图像和一些数据上传到 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/

相关文章:

ios - 如何在编辑时将“编辑”按钮变成“完成”?

iOS swift : Calling a singleton method 3 times causes app to crash

javascript - 当应用程序最小化/关闭时更新 Firestore 值

ios - 如何在我的应用程序中重用默认的 iPhone 应用程序功能?

ios - 核心数据计算和数据分组

android - 在构造不可变类 com 时发现字段 'rangeStart' 不受支持的类型 (com.google.gms.googleservices.GoogleServicesPlugin$Version)

node.js - 限制对 admin-sdk 的 firestore 访问

ios - 在 View 层次结构中保持 UITabBarController 可见( Storyboard)

ios - iPad 和 iPad mini 纵向键盘高度一样吗?

ios - NSPredicate 用于选择中间给定对象