WatchOS 3 NSURLSession download task fails with "no such file or directory"

I'm trying to update my complication in the background by using a NSURLSessionDownloadTask. I'm able to kickoff the download task at the expected time in the background using this code:


func loadTransitServicesForComplication() {
  if let transitStop = transitStops?.first, baseUrl = transitStop.transitRegionUrls.first {
  let backgroundConfigObject = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("io.getembark.embark.watch.complicationBackgroundSession")
  backgroundConfigObject.sessionSendsLaunchEvents = true
  backgroundConfigObject.HTTPAdditionalHeaders = SkedGoAPIController.requestHeaders()

  backgroundURLSession?.invalidateAndCancel()
  let backgroundSession = NSURLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
  backgroundURLSession = backgroundSession

  if let url = NSURL(string: baseUrl + "/departures.json") {
  let request = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
  request.HTTPMethod = "POST"
  let parameters = SkedGoAPIController.parametersForLoadTransitServicesForTransitStop(transitStop)
  do {
  let jsonData = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
  request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length")
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  request.setValue("application/json", forHTTPHeaderField: "Accept")

  request.HTTPBody = jsonData
  NSURLSessionDownloadTask
  let downloadTask = backgroundSession.downloadTaskWithRequest(request)
  print("resuming request")
  downloadTask.resume()
  }
  catch {}

  }
  }

}


These are my delegate callbacks:


func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  if let data = NSFileManager.defaultManager().contentsAtPath(location.path!) {
  do {
  let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
  print(json)
  }
  catch {}
  }
  else {
  print("data could not be read")
  }
  print(location)
  }


  func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  print("downloading...")
  }

  func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  if let error = error {
  print(error)
  }
  else {
  print("done")
  }

}


I usually run into one or two problems:


1. session:task:didCompleteWithError is called with this error:

Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory" UserInfo={NSErrorFailingURLKey=https://granduni-au-nsw-sydney.tripgo.skedgo.com/satapp/departures.json, NSErrorFailingURLStringKey=https://granduni-au-nsw-sydney.tripgo.skedgo.com/satapp/departures.json}


OR

2. session:downloadTask:didFinishDownloadToURL is called, and the location URL is populated, for example:

file:///Users/Ben/Library/Developer/CoreSimulator/Devices/DA0DA24C-083D-4C70-AF26-675D7004B25D/data/Containers/Data/PluginKitPlugin/E8E12C5A-ACFC-493B-9607-0FB865873CF1/Library/Caches/com.apple.nsurlsessiond/Downloads/io.getembark.embark.watchkitapp.watchkitextension/CFNetworkDownload_XGHXpA.tmp

However, loading the file using NSFileManager fails, and if I navigate to that URL on my local system, the file does not exist. Interestingly, it is not just that the file doesn't exist, it's the whole application folder (E8E12C5A-ACFC-493B-9607-0FB865873CF1). This folder is simply not there.

Am I doing something wrong?

Replies

Exactly the same issue here. There is an old radar for this already, but still unresolved http://www.openradar.me/21950485

Exactly the same problem here. The response with the headers come with a status code 200. However, the error delegate is still called.

Apparently this was fixed now with XCode 8.3. Same code that got me the mentioned errors now works fine.