Johnny  Hsieh Johnny Hsieh - 4 months ago 35
Swift Question

Uibutton to pass location information and start to navigation on map in swift

I have a array content of CLLocationcooridinate2d and location detail. And I put it on tableview cell with Uibutton, what Im doing is trying to pass the specific cell information by Uibuttom and start a new view of map view and began to navigation. Here is my code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MapCell") as! mapTableViewCell
if searchController.active{
cell.title.text = searchResults[indexPath.row].title
cell.location.text = searchResults[indexPath.row].location
cell.naviButton.tag = indexPath.row
cell.naviButton.addTarget(self, action: Selector("tapDidNavi"), forControlEvents: .TouchUpInside)

return cell
}else{
cell.title.text = tripspot[indexPath.row].title
cell.location.text = tripspot[indexPath.row].location
cell.naviButton.tag = indexPath.row
cell.naviButton.addTarget(self, action: Selector("tapDidNavi"), forControlEvents: .TouchUpInside)
print(cell.naviButton.tag.description)
return cell
}


}

@IBAction func tapDidNavi(sender: UIButton){



}


thanks for any advice!

Answer

You can use MKMapItem.openMapsWithItems:launchOptions: to start turn-by-turn navigation in the Maps app.

From the documentation:

If you specify the MKLaunchOptionsDirectionsModeKey option in the launchOptions dictionary, the mapItems array must have no more than two items in it. If the array contains one item, the Maps app generates directions from the user’s current location to the location specified by the map item. If the array contains two items, the Maps app generates directions from the location of the first item to the location of the second item in the array.

@IBAction func tapDidNavi(sender: UIButton){

    let coordinate = coordinates[sender.tag]

    let placemark = MKPlacemark(
        coordinate: coordinate, 
        addressDictionary: nil
    )

    let mapItem = MKMapItem(placemark: placemark)

    let options = [
        MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving
    ]

    MKMapItem.openMapsWithItems([mapItem], launchOptions: options)
}