1

I have an application that retrieves JSON data from my server and enters it in to my Core Data model. I have this working reasonably well, minus a few issues with random EXC_BAD_ACCESS errors that I haven't figured out yet. During this dataTask, it can retrieve large amounts of data so it can take a while to complete.

I'm looking for a way to let the user suspend the app the dataTask will continue to retrieve the data. I seen NSURLSession has a background mode, but seen it only supports upload and download tasks.

Is there a way to support this?

My dataTask function:

class func Request(file: String, withData: String?, completion: (NSData -> Void)) {
    let url = NSURL(string: "\(root)\(file)")!

    let request = NSMutableURLRequest(URL: url)

    if let sentData = withData {
        request.HTTPMethod = "POST"
        request.HTTPBody = sentData.dataUsingEncoding(NSUTF8StringEncoding)
    }

    let dataTask = session.dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            if error?.domain == NSURLErrorDomain && error?.code == NSURLErrorTimedOut {
                print("Data task timed out")
            }
        } else {
            let httpResponse : NSHTTPURLResponse = response as! NSHTTPURLResponse

            if httpResponse.statusCode == 200 {
                completion(data!)
            } else {
                print("Request failed with status code: \(httpResponse.statusCode)")
            }
        }
    }
    dataTask.resume()
}
Sawyer05
  • 1,604
  • 2
  • 22
  • 37
  • App will failed to download task while app is forcefully quit and NSURL session has a mode of background queue you can use it too check this link http://stackoverflow.com/questions/24209539/background-transfer-download-task-failed-when-app-was-closed – Muhammad Waqas Bhati Sep 01 '15 at 09:01
  • 1
    Hi Muhammad, I'm not looking to forcefully quit the app, just suspend it into the background. As far as I could tell from Apple's documentation, the NSURLSession background queue only supports download and upload tasks, not data tasks – Sawyer05 Sep 01 '15 at 09:05
  • @Sawyer05 did you ever find a solution to this? – Guy Kogus Dec 20 '18 at 01:16

0 Answers0