我正在使用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
}
}
编辑:找到错误的原因.
由于在Called View Controller中创建了NSURLSession而发生错误.Called 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,delegateQueue: NSOperationQueue.mainQueue())
}
func downloadPDF() {
//Download PDF
download_task = backgroundSession.downloadTaskWithURL(url)
download_task?.resume()
}
}
解决方法
在MainFormsController中添加以下代码:
deinit {
self.backgroundSession.finishTasksAndInvalidate();
}