URLSession
data task block is not calling when the app is in background and it stuck at dataTask
with request.
When I open the app the block gets called. By the way I'm using https
request.
This is my code:
let request = NSMutableURLRequest(url: URL(string: url as String)!,
cachePolicy: .reloadIgnoringCacheData,
timeoutInterval:20)
request.httpMethod = method as String
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let data = params.data(using: String.Encoding.utf8.rawValue)
request.httpBody = data
session.dataTask(with: request as URLRequest,completionHandler:
{(data, response, error) -> Void in
if error == nil
{
do {
let result = try JSONSerialization.jsonObject(with: data!, options:
JSONSerialization.ReadingOptions.mutableContainers)
print(result)
completionHandler(result as AnyObject?,nil)
}
catch let JSONError as NSError{
completionHandler(nil,JSONError.localizedDescription as NSString?)
}
}
else{
completionHandler(nil,error!.localizedDescription as NSString?)
}
}).resume()
Working perfectly when the app is in active state. Is there anything wrong in my code. please point me
You need a background session. The URLSessionDataTask which as per Apple's documentation doesn't support background downloads.
Create a
URLSessionDownloadTask
and use its delegate method it should work.Follow this link
// Apply as shown in picture
/*********************/
If you want downloads to progress after your app is no longer in foreground, you have to use background session. The basic constraints of background sessions are outlined in URL Session Programming Guide: Using NSURLSession: Background Transfer Considerations, and are essentially:
Use delegate-based
URLSession
with backgroundURLSessionConfiguration
.Use upload and download tasks only, with no completion handlers.
Implement
application(_:handleEventsForBackgroundURLSession:completionHandler:)
in your app delegate, saving the completion handler and starting your background session.Implement
urlSessionDidFinishEvents(forBackgroundURLSession:)
in yourURLSessionDelegate
, calling that saved completion handler to let OS know you're done processing the background request completion.So, pulling that together:
Where
And the app delegate does: