2

I would like to upload an image and some data to Firebase Storage and Firebase Firestore. I have all the code working but when I leave the app the upload stops. Is there any possible way to keep the task running in the background?

I know it is possible with URLSession but I don't know how to do it using Firebase.

Summary:

I would like to upload data to Firebase in the background (when the app is closed) in Swift.

Thanks in advance!

  • look into these links 1. https://github.com/firebase/firebase-ios-sdk/issues/147 2. https://stackoverflow.com/questions/44241093/write-data-to-firebase-in-the-background-after-retrieving-steps-with-healthkits – Gagan_iOS Apr 06 '19 at 22:12

1 Answers1

1

This code seemed to work:

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()
    }
  }
}

Thanks @Gagan_iOS! Source: https://github.com/firebase/firebase-ios-sdk/issues/147