1

I am working on a app using MapView now have an issue kindly help me to figure out.

  • I placed a search bar when user types the name of a place then it gives suggestions based upon the string entered.

  • Using mapkit, I am able to send query to default maps, receive MKLocalSearchResponse.

Now My problem is data from LocalSearchResponse is not getting displayed in tableView cells.

please kindly provide an solution.

Using tools: Xcode 7.3, swift 2.2

Here is my code kindly have a look.

import UIKit
import MapKit
class ViewController: UIViewController, UISearchBarDelegate,UITableViewDelegate {

var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var items1:String = ""

var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var matchingItems: [MKMapItem] = [MKMapItem]()
var mapItems: [MKMapItem] = [MKMapItem]()
var itm : [String] = []

@IBAction func showSearchBar(sender: AnyObject) {
    searchController = UISearchController(searchResultsController: nil)
    searchController.hidesNavigationBarDuringPresentation = false
    self.searchController.searchBar.delegate = self
    presentViewController(searchController, animated: true, completion: nil)

}

@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

    func searchBarSearchButtonClicked(searchBar: UISearchBar){

    searchBar.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    if self.mapView.annotations.count != 0{
        annotation = self.mapView.annotations[0]
        self.mapView.removeAnnotation(annotation)
    }

    localSearchRequest = MKLocalSearchRequest()
    localSearchRequest.naturalLanguageQuery = searchBar.text
    localSearch = MKLocalSearch(request: localSearchRequest)
    localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in

        if localSearchResponse == nil{
            let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alertController, animated: true, completion: nil)
            return
        }

        for item in localSearchResponse!.mapItems {

            print("Name = \(item.name)")
            self.items1 = item.name!

            self.matchingItems.append(item as MKMapItem)
            print("Matching items = \(self.matchingItems.count)")
                }
        self.pointAnnotation = MKPointAnnotation()
        self.pointAnnotation.title = searchBar.text
        self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude:     localSearchResponse!.boundingRegion.center.longitude)


        self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
        self.mapView.centerCoordinate = self.pointAnnotation.coordinate
        self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
    }

}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchingItems.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let entry = matchingItems[indexPath.row]
cell.textLabel!.text = items1[indexPath.row]

return cell
}

}

vaibhav
  • 4,038
  • 1
  • 21
  • 51
Guru Teja
  • 127
  • 2
  • 13

1 Answers1

0
  1. set the delegate and datasource of your tableView to the associated viewController using the storyboard properly see image
  2. Add delegate and datasuorce both seprating with comma like UITableViewDataSource, UITableViewDelegate in your class.

enter image description here

now you dont need to set the delegate inside the program.

  • call reloadData() function each and everytime when you type a single word or accordingly.
vaibhav
  • 4,038
  • 1
  • 21
  • 51
  • Is there any way to clear the table view cells content every time user searches again and How to find whether user is typing or finished or canceled. I am using bar button item not search bar. – Guru Teja Aug 19 '16 at 14:59
  • @GuruTeja you can detect user typing by using `shouldChangeCharactersInRange` [**delegate method**](http://code.tutsplus.com/tutorials/ios-sdk-uitextfield-uitextfielddelegate--mobile-10943) of `uitextfield` .. – vaibhav Aug 20 '16 at 09:40
  • why cant we use func textFieldShouldEndEditing(textField: UITextField) -> Bool. – Guru Teja Aug 30 '16 at 09:08