2017-05-27 72 views
3

我想提請當前用戶位置的折線來註釋一點,但它似乎並沒有畫任何東西:繪製折線與mapkit斯威夫特3

@IBAction func myButtonGo(_ sender: Any) { 
    showRouteOnMap() 
} 

func showRouteOnMap() { 
    let request = MKDirectionsRequest() 

    request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D.init(), addressDictionary: nil)) 
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: (annotationCoordinatePin?.coordinate)!, addressDictionary: nil)) 
    request.requestsAlternateRoutes = true 
    request.transportType = .automobile 

    let directions = MKDirections(request: request) 

    directions.calculate { [unowned self] response, error in guard let unwrappedResponse = response else { return } 

     if (unwrappedResponse.routes.count > 0) { 
      self.mapView.add(unwrappedResponse.routes[0].polyline) 
      self.mapView.setVisibleMapRect(unwrappedResponse.routes[0].polyline.boundingMapRect, animated: true) 
     } 
    } 
} 

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { 
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline) 
    renderer.strokeColor = UIColor.black 
    return renderer 
} 

我試圖在調試模式下,它運行在線處斷點處停止:

directions.calculate { [unowned self] response, error in guard let unwrappedResponse = response else { return } 

這個錯誤的原因是什麼?

回答

1

如果它停在那裏,請確保你沒有一個斷點:

enter image description here

在左邊距深藍色指標表明有一個斷點。如果你有一個斷點,只需點擊它就可以禁用它(將其改爲淡藍色)或將其拖出以將其刪除。

如果不是(即它的真正崩潰),那麼我們需要知道如果它不崩潰什麼樣的崩潰是什麼在控制檯中露面等

的,但根本就沒有繪製問題路線,確保你已經指定了地圖視圖的delegate(在viewDidLoad或右邊的IB)。


話雖如此,一對夫婦的其他意見,但:

  1. 你的起點座標是CLLocationCoordinate2D()(即lat和長0,0,即在太平洋)。這不會導致崩潰,但如果檢查error對象,它的本地化描述會說:

    路線不可用

    你應該糾正coordinatesource

  2. 你應該警惕unowned self與異步方法,因爲總是有可能self可以釋放到指令返回時,它會崩潰。使用[weak self]更安全。

因此:

let request = MKDirectionsRequest() 
request.source = MKMapItem(placemark: MKPlacemark(coordinate: sourceCoordinate)) 
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destinationCoordinate)) 
request.requestsAlternateRoutes = true 
request.transportType = .automobile 

let directions = MKDirections(request: request) 
directions.calculate { [weak self] response, error in 
    guard let response = response, error == nil, let route = response.routes.first else { 
     print(error?.localizedDescription ?? "Unknown error") 
     return 
    } 

    self?.mapView.add(route.polyline) 
}