title: Implementing completion handlers for backgroundSession.uploadTask
body: <p>I have (almost) successfully implemented <code>URLSessionDelegate</code>, <code>URLSessionTaskDelegate</code>, and <code>URLSessionDataDelegate</code> so that I can upload my objects in the background. But I'm not sure how to implement completion handlers, so that I can delete the object that I sent, when the server returns <code>statuscode=200</code></p>
  
  <p>I currently start the <code>uploadTask</code> like this</p>
  
  <pre><code>let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.myObject\(myObject.id)")
  let backgroundSession = URLSession(configuration: configuration, 
                                     delegate: CustomDelegate.sharedInstance, 
                                     delegateQueue: nil)
  let url: NSURL = NSURL(string: "https://www.myurl.com")!
  let urlRequest = NSMutableURLRequest(url: url as URL)
  
  urlRequest.httpMethod = "POST"
  urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
  
  let uploadTask = backgroundSession.uploadTask(with: urlRequest as URLRequest, fromFile: path)
  
  uploadTask.resume()
  </code></pre>
  
  <p>I tried adding a closure to the initialization of <code>uploadTask</code> but xcode displayed an error that it was not possible.</p>
  
  <p>I have my custom class CustomDelegate:</p>
  
  <pre><code>class CustomDelegate : NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
  
  static var sharedInstance = CustomDelegate()
  
  func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
      print("\(session.configuration.identifier!) received data: \(data)")
      do {
          let parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
          let status = parsedData["status"] as! NSDictionary
          let statusCode = status["httpCode"] as! Int
  
          switch statusCode {
          case 200:
              // Do something
          case 400:
              // Do something
          case 401:
              // Do something
          case 403:
              // Do something
          default:
              // Do something
          }
      }
      catch {
          print("Error parsing response")
      }
  }
  }
  </code></pre>
  
  <p>It also implements the other functions for the delegates.</p>
  
  <p>What I want is to somehow know that the upload is done so that I can update the UI and database which I feel is hard (maybe impossible?) from within <code>CustomDelegate</code>.</p>