【发布时间】:2016-03-22 11:40:04
【问题描述】:
我正在使用 NSURLSession 和 NSURLSessionDelegate 从服务器获取 xml 数据。取决于我与服务器连接的某些条件。如果我与服务器连接一切正常,没有任何错误,但如果我没有连接(取决于条件)到服务器并移动到另一个视图控制器(通过使用故事板?.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
}
}
编辑:找到错误原因。
由于在被调用视图控制器中创建 NSURLSession 而发生错误。被调用 VC 包含从服务器下载 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()
}
}
【问题讨论】: