NSURLSession didCompleteWithError: how to determine what task it is?

NSURLSession didCompleteWithError: how to determine what task it is?

我有一个 class 符合用于下载数据的 NSURLSession 委托,并且在完成后调用多个服务时出现问题,他们调用方法 func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?),结果在这里被解析和处理以返回到正确的视图控制器。

我如何知道结果来自哪个会话或任务,以便调用正确的视图控制器?

import Foundation


class Support{

// MARK - Properties
var ID: Int!
var SoftekID: String!
var Subject: String!
var LastUpdate: String!
var LastUpdatedBy: String!
var Priority: Int!
var Impact: Int!
var SupportType: String!
var Importance: Int!


// MARK: General
init() {
    self.ID = 0
    self.SoftekID = ""
    self.Subject = ""
    self.LastUpdate = ""
    self.LastUpdatedBy = ""
    self.Priority = 0
    self.Impact = 0
    self.SupportType = ""
    self.Importance = 0
}

func getSupportTickets(){
let sp = SuppportProvider()
    sp.getSupportTickets()
}
}

class SuppportProvider: NSObject, NSURLSessionDelegate,      NSURLSessionDataDelegate, NSURLSessionTaskDelegate{

// MARK: - Properties
var mData: NSMutableData?
var session: NSURLSession!

override init(){
    super.init()
    prepareConnection()
}

// MARK: - Methods
func prepareConnection(){

    session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue:nil)
}

func getSupportTickets(){
    var request = NSMutableURLRequest(URL: NSURL(string: "http://10.0.58.137/ISOWeb.UI/api/CSMobile/GetSupportTickets?PageNumber=0&PagingSize=10&TicketStatus=Priority")!,
        cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy,
        timeoutInterval: 20.0)

    let task =  session.dataTaskWithRequest(request)

    mData = NSMutableData()
    task.resume()
}

func getHelpInformation(){
    var request = NSMutableURLRequest(URL: NSURL(string: "http://10.0.58.137/ISOWeb.UI/api/CSMobile/GetHelpInformation")!,
        cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy,
        timeoutInterval: 20.0)

    let task = session.dataTaskWithRequest(request)

    mData = NSMutableData()
    task.resume()
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

    mData!.length = 0
    completionHandler(NSURLSessionResponseDisposition.Allow)
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {

    mData!.appendData(data)
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {

    if error != nil{
        println("An error has occured completing the request")
    }else{

        //Result for method: getSupportTickets
        var value = NSString(bytes: mData!.mutableBytes, length: mData!.length, encoding: NSUTF8StringEncoding)

        var jError: NSError?

        if let JSONResult: Array<NSDictionary> = NSJSONSerialization.JSONObjectWithData(mData!, options: NSJSONReadingOptions.AllowFragments, error: &jError) as? Array<NSDictionary> {

            if JSONResult.count > 0 {

               var arr = Array<Support>()

                for dict in JSONResult{

                    let item = Support()

                    if (dict["ID"] as? Int != nil) {
                        item.ID = dict["ID"] as! Int
                    }else {
                        item.ID = 0
                    }

                    if (dict["SoftekID"] as? String != nil) {
                        item.SoftekID = dict["SoftekID"] as! String
                    }else {
                        item.SoftekID = ""
                    }

                    if (dict["Subject"] as? String != nil) {
                        item.Subject = dict["Subject"] as! String
                    }else {
                        item.Subject = ""
                    }

                    if (dict["LastUpdate"] as? String != nil) {
                          item.LastUpdate = dict["LastUpdate"] as! String
                    }else {
                        item.LastUpdate = ""
                    }

                    if (dict["LastUpdatedBy"] as? String != nil) {
                         item.LastUpdatedBy = dict["LastUpdatedBy"] as! String
                    }else {
                        item.LastUpdatedBy = ""
                    }

                    if (dict["Priority"] as? Int != nil) {
                         item.Priority = dict["Priority"] as! Int
                    }else {
                         item.Priority = 0
                    }

                    if (dict["Impact"] as? Int != nil) {
                        item.Impact = dict["Impact"] as! Int
                    }else {
                        item.Impact = 0
                    }

                    if (dict["SupportType"] as? String != nil) {
                         item.SupportType = dict["SupportType"] as! String
                    }else {
                        item.SupportType = ""
                    }

                    if (dict["Importance"] as? Int != nil) {
                        item.Importance = dict["Importance"] as! Int
                    }else {
                        item.Importance = 0
                    }

                    arr.append(item)
                }
            }
        }

        //Result for method: getHelpInformation
        //How to know to which task holds the result?
    }
}

}

更新

import Foundation

class CSSupport{

// MARK - Properties
var ID: Int!
var SoftekID: String!
var Subject: String!
var LastUpdate: String!
var LastUpdatedBy: String!
var Priority: Int!
var Impact: Int!
var SupportType: String!
var Importance: Int!


// MARK: General
init() {
    self.ID = 0
    self.SoftekID = ""
    self.Subject = ""
    self.LastUpdate = ""
    self.LastUpdatedBy = ""
    self.Priority = 0
    self.Impact = 0
    self.SupportType = ""
    self.Importance = 0
}
}

class Support:NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate, NSURLSessionTaskDelegate{

// MARK: - Properties
var mData: NSMutableData?
var session: NSURLSession!

 override init(){
    super.init()
    var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    session = NSURLSession(configuration:configuration, delegate: self, delegateQueue:nil)
}

// MARK: - Methods
func getSupportTickets(){
    var request = NSMutableURLRequest(URL: NSURL(string: "http://10.0.58.137/ISOWeb.UI/api/CSMobile/GetSupportTickets?PageNumber=0&PagingSize=10&TicketStatus=Priority")!,
        cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy,
        timeoutInterval: 20.0)

    let task =  session.dataTaskWithRequest(request)

    mData = NSMutableData()
    task.resume()
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

    mData!.length = 0
    completionHandler(NSURLSessionResponseDisposition.Allow)
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {

    mData!.appendData(data)
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {

    if error != nil{
        println("An error has occured completing the request")
    }else{

         var value = NSString(bytes: mData!.mutableBytes, length: mData!.length, encoding: NSUTF8StringEncoding)
         var jError: NSError?

        switch task.taskIdentifier {
        case 1:
            if let JSONResult: Array<NSDictionary> = NSJSONSerialization.JSONObjectWithData(mData!, options: NSJSONReadingOptions.AllowFragments, error: &jError) as? Array<NSDictionary> {

                if JSONResult.count > 0 {

                    var arr = Array<CSSupport>()

                    for dict in JSONResult{

                        let item = CSSupport()

                        if (dict["ID"] as? Int != nil) {
                            item.ID = dict["ID"] as! Int
                        }else {
                            item.ID = 0
                        }

                        if (dict["SoftekID"] as? String != nil) {
                            item.SoftekID = dict["SoftekID"] as! String
                        }else {
                            item.SoftekID = ""
                        }

                        if (dict["Subject"] as? String != nil) {
                            item.Subject = dict["Subject"] as! String
                        }else {
                            item.Subject = ""
                        }

                        if (dict["LastUpdate"] as? String != nil) {
                            item.LastUpdate = dict["LastUpdate"] as! String
                        }else {
                            item.LastUpdate = ""
                        }

                        if (dict["LastUpdatedBy"] as? String != nil) {
                            item.LastUpdatedBy = dict["LastUpdatedBy"] as! String
                        }else {
                            item.LastUpdatedBy = ""
                        }

                        if (dict["Priority"] as? Int != nil) {
                            item.Priority = dict["Priority"] as! Int
                        }else {
                            item.Priority = 0
                        }

                        if (dict["Impact"] as? Int != nil) {
                            item.Impact = dict["Impact"] as! Int
                        }else {
                            item.Impact = 0
                        }

                        if (dict["SupportType"] as? String != nil) {
                            item.SupportType = dict["SupportType"] as! String
                        }else {
                            item.SupportType = ""
                        }

                        if (dict["Importance"] as? Int != nil) {
                            item.Importance = dict["Importance"] as! Int
                        }else {
                            item.Importance = 0
                        }

                        arr.append(item)
                    }
                }
            }
            break

        case 2:

            break

        default:
            println("No task was found.")
            break
        }
    }
}

}

也许 taskIdentifier 属性 可以帮助您:https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTask_class/index.html#//apple_ref/occ/instp/NSURLSessionTask/taskIdentifier

是的,缺少任何类型的可自定义存储有点烦人,特别是因为标识符仅在每个会话的基础上是唯一的。有几种方法可以解决这个问题:

  • 如果您正在使用后台会话或前景和后台会话的混合,我认为您可以做的最好的事情是两级查找,其中您将可变字典与每个关联session 并首先查找会话,然后在每个会话字典中通过其标识符查找任务:

    • 对于后台会话,提供一个标识符以用作顶级可变字典中的键。
    • 对于其他会话,使用会话对象本身作为顶级可变字典中的键。
  • 如果您只使用前台任务(而不是在后台会话中),您应该能够将任务用作字典键并查找与任务相关的其他数据.

认为 这两种技术应该都能正常工作。您还可以使用任务中的关联对象来存储额外数据(只要您不使用后台会话)。

你绝对不能做的一件事(我已经提交了一个关于这个的错误)是子类 NSURLRequest 并在那里存储额外的数据,因为 NSURLSession returns 它自己的 NSURLRequest 副本(而不是你的自定义子类) 当你请求 currentRequest 时,returns 当你请求 orginalRequest 时,你的子类的一个看似随机的实例(与实际的原始请求无关)。

令人惊奇的是,每个人都必须付出多少努力来创建外部词典来解决每个任务和每个会话中缺少简单 refCon 对象 属性 的问题。提交错误以请求该功能绝对值得。

为什么不在属于 NSURLSessionTask 的 taskDescription 中使用您自己的自定义字符串标识符?