如何在完成处理程序块中处理已取消的NSURLSessionTask?

Dou*_*ith 13 cocoa-touch ios nsurlsession nsurlsessiondownloadtask swift

如果我创建一个NSURLSessionDownloadTask,然后在它完成之前取消它,完成块似乎仍然会触发.

let downloadTask = session.downloadTaskWithURL(URL, completionHandler: { location, response, error in 
    ...
}
Run Code Online (Sandbox Code Playgroud)

如何在此块中检查下载任务是否已取消,以便在没有下载任务时不尝试对下载操作进行操作?

Rob*_*Rob 28

对于下载任务,将使用nil值来调用完成处理程序,并且对象locationcodeNSError将是NSURLErrorCancelled.在Swift 3中:

let task = session.downloadTask(with: url) { location, response, error in
    if let error = error as? NSError {
        if error.code == NSURLErrorCancelled {
            // canceled
        } else {
            // some other error
        }
        return
    }

    // proceed to move file at `location` to somewhere more permanent
}
task.resume()
Run Code Online (Sandbox Code Playgroud)

或者在Swift 2中:

let task = session.downloadTaskWithURL(url) { location, response, error in
    if let error = error {
        if error.code == NSURLErrorCancelled {
            // canceled
        } else {
            // some other error
        }
        return
    }

    // proceed to move file at `location` to somewhere more permanent
}
task.resume()
Run Code Online (Sandbox Code Playgroud)

同样,对于数据任务,将使用Error/ 来调用完成处理程序,该/ NSError表示是否已取消.在Swift 3中:

let task = session.dataTask(with: url) { data, response, error in
    if let error = error as? NSError {
        if error.code == NSURLErrorCancelled {
            // canceled
        } else {
            // some other error
        }
        return
    }

    // proceed to move file at `location` to somewhere more permanent
}
task.resume()
Run Code Online (Sandbox Code Playgroud)

或者在Swift 2中:

let task = session.dataTaskWithURL(url) { data, response, error in
    if let error = error {
        if error.code == NSURLErrorCancelled {
            // canceled
        } else {
            // some other error
        }
        return
    }

    // otherwise handler data here
}
task.resume()
Run Code Online (Sandbox Code Playgroud)