I have a searchBar
. When you type in the searchBar
(at least 3 character) a request with the searchString
is sent to a server. This server response with a XML. This XML is parsed. A list is displayed to the user.
Each time the user type in the searchBar a new request is sent and a new list is displayed.
This is part of my code:
let url = NSURL(string: "\(Paises.sharedInstance.getUrlPaisActual())?tipo=3&v=3&p=\(Paises.sharedInstance.getIdPaisActual())&texto=\(searchString)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
}
task.resume()
This work well when the network is fine. But when the network is slow, the responses don't arrive in the same order in which they are submitted.
How can I fix this? Can I know if a response is outdated? Maybe with a timeout?
Thanks.
Updated with Wain's answer:
This is the static var where I store my token.
struct RequestToken {
static var identificador = 0
func incrementar() -> Int {
return ++RequestToken.identificador
}
}
This is the new request:
let url = NSURL(string: "\(Paises.sharedInstance.getUrlPaisActual())?tipo=3&v=3&p=\(Paises.sharedInstance.getIdPaisActual())&texto=\(searchString)")
let identificador = RequestToken().incrementar()
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if identificador == RequestToken.identificador {
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
}
}
task.resume()
Thank you very much Wain.