title: URLSession Cancellation in swift while auto search
body: <p>My moto is Auto search, I have been trying with URLSession, When i am trying to search slowly the requests are handled as expected(when there is no text the response is empty i mean the placesarray) but when i am trying to clear the text or hit any searchtext speedily then the previous request response are being appended in the placesarray. I tried with cancelling the previous request yet i am not getting the result(i.e previous response not be appended)</p>
  
  <pre><code>func autoSearch(text:String){    
     let urlRequest = URLRequest(url: self.getQueryFormedBingURL()!)
  
     let session = URLSession.shared
     session.getTasksWithCompletionHandler
     {
        (dataTasks, uploadTasks, downloadTasks) -&gt; Void in
        // self.cancelTasksByUrl(tasks: dataTasks     as [URLSessionTask])
        self.cancelTasksByUrl(tasks: uploadTasks   as [URLSessionTask])
        self.cancelTasksByUrl(tasks: downloadTasks as [URLSessionTask])
     }
     let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) -&gt; Void in
  
     print("response \(response)")
  
     if let data = data {
  
        let json = try? JSONSerialization.jsonObject(with: data, options: [])
  
        if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
  
           if let jsonDic = json as? NSDictionary {
  
               let status = jsonDic.returnsObjectOrNone(forKey: "statusCode") as! Int
  
                if status == 200 {
  
                   if let resourceSetsArr = jsonDic.returnsObjectOrNone(forKey: "resourceSets") as? NSArray {
  
                      if let placesDict = resourceSetsArr.object(at: 0) as? NSDictionary {
                         if let resourceArr = placesDict.object(forKey: "resources") as? NSArray, resourceArr.count &gt; 0 {
  
                            if let _ = self.placesArray {
                               self.placesArray!.removeAll()
                            }
                            for loopCounter in 0...resourceArr.count - 1 {
                               let modalClass:BingAutoCompletePlace = BingAutoCompletePlace(responseDict: resourceArr[loopCounter] as! NSDictionary)
                               self.placesArray?.append(modalClass)
                            }
                            completion(self.placesArray!)
                         }
                         else { //URL Success, where there no places with the given search string
                            completion([])
                         }
                      }
                   }
                }
             }
          }
          else if let response = response as? HTTPURLResponse , 400...499 ~= response.statusCode {// When url fails
                  if let _ = error {
                     print("error=\(error!.localizedDescription)")
                  }
                  completion([])
               }
               else {
                  if let _ = error {
                     print("error=\(error!.localizedDescription)")
                  }
                  completion([])
               }
           }
       })
       task.resume()
  }
  </code></pre>
  
  <p>//Request cancellation</p>
  
  <pre><code>private func cancelTasksByUrl(tasks: [URLSessionTask]) {
     for task in tasks
     {
        task.cancel()
     }
  }
  </code></pre>