Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A background URLSession with identifier backgroundSession already exists

Tags:

ios

swift

I'm fetching xml data from server by using NSURLSession and NSURLSessionDelegate. Depends on some conditions I'm connecting with server. If I'm connecting with server everything works fine without any error but if I'm not connecting (depends on condition) to server and moving to another View Controller (by using storyboard?.instantiateViewControllerWithIdentifier(id)) I'm getting the following IOS error:

'A background URLSession with identifier backgroundSession already exists!'

Here is my code:

class MainClass: UITableViewController, NSURLSessionDelegate {     

   var task_service = NSURLSessionDataTask?()

   override func viewDidLoad() {
      super.viewDidLoad()

      if(condition) {
        getXMLFromServer()
      }

   }

   func getXMLFromServer(){

     task_service = getURLSession().dataTaskWithRequest() {

        (data, response, error) -> Void in

        dispatch_async(dispatch_get_main_queue(), {

         // Fetching data from server 

         // In the end
         self.session.invalidateAndCancel()
       }
    }

  }

 func getURLSession() -> NSURLSession {

    let configuration =      NSURLSessionConfiguration.defaultSessionConfiguration()

    configuration.timeoutIntervalForRequest = 30.0

    session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

    return session
  }

 func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

    completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)) // Bypassing SSL error
 }   
}

EDIT: Found the reason for the error.

Error occurred because of the creation of NSURLSession in the Called View Controller.Called VC contains code to download PDF from server. But I don't know how to solve this. Below is the code of Called VC

class MainFormsController: UIViewController, UIPickerViewDelegate, UITextFieldDelegate, NSURLSessionDownloadDelegate, UIDocumentInteractionControllerDelegate, MFMailComposeViewControllerDelegate{

 var download_task = NSURLSessionDownloadTask?()
 var backgroundSession = NSURLSession()

 override func viewDidLoad() {
    super.viewDidLoad()

     createNSURLSession()
 }               

 /** Error occurred while creating this NSURLSession **/

    func createNSURLSession() { 

        let backgroundSessionConfiguration =  NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession")

       backgroundSession = NSURLSession(configuration:   backgroundSessionConfiguration, delegate: self, delegateQueue:   NSOperationQueue.mainQueue())
    }

  func downloadPDF() {

     //Download PDF
     download_task = backgroundSession.downloadTaskWithURL(url)
     download_task?.resume()
  }

}
like image 949
vsvishnu Avatar asked Mar 22 '16 11:03

vsvishnu


Video Answer


1 Answers

Your code probably calls createNSURLSession() more than once which invalidate the NSURLSession behavior, as documentation says:

"You must create exactly one session per identifier (specified when you create the configuration object). The behavior of multiple sessions sharing the same identifier is undefined."

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html

Make sure createNSURLSession is called only once (singletone) for the life cycle of your app.

like image 106
Amir Aharon Avatar answered Sep 19 '22 14:09

Amir Aharon