我正在使用NSURLSession和NSURLSessionDelegate从服务器获取xml数据。取决于某些条件,我正在与服务器连接。如果我与服务器连接,一切正常,没有任何错误,但是如果我没有连接(取决于条件)到服务器并移动到另一个View Controller(通过使用Storyboard?.instantiateViewControllerWithIdentifier(id)),我将得到以下信息iOS错误:

“标识符为backgroundSession的后台URLSession已经存在!”

这是我的代码:

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
 }
}

编辑:找到错误的原因。

由于在Called View Controller中创建了NSURLSession而发生了错误。CalledVC包含从服务器下载PDF的代码。但是我不知道如何解决这个问题。以下是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()
  }

}

最佳答案

在您的MainFormsController中添加以下代码:

deinit {
        self.backgroundSession.finishTasksAndInvalidate();
    }

10-07 21:24
查看更多