2017-02-03 3 views
1

Я использую Alamofire для запроса данных с сервера, а затем используйте эти данные для отображения местоположения на карте. При панорамировании или масштабировании карты требуется запросить API и перезагрузить карту.Запрос с Alamofire и Mapkit Swift 3

Текущая проблема заключается в том, что при масштабировании или панорамировании CPU> 100% приводит к невозможности масштабирования и панорамирования.

Мой код ниже:

Alamofire Запрос:

func getResultMap() { 
    DispatchQueue.main.async(execute: { 
     self.skipSearchRequest = true 

     SearchWebservice.sharedInstance.getResultMap(currentSearchObject, success: { (result) in 
      var clusters: [Cluster] = [] 
      var markers : [Marker] = [] 
      if self.mapLayerType == .ClusterOverview { 
       for item in result.clusterOverview { 
        clusters.append(item) 
       } 
       self.setMapAnnotations(annotations: clusters) 
      } else { 
       for item in result.markers { 
        markers.append(item) 
       } 
       self.addMapAnnotations(annotations: markers) 
      } 
      self.skipSearchRequest = false 
     }) { (error) in 
      print(error) 
     } 
    }) 
} 

Add/Remove Аннотация:

func addMapAnnotations(annotations: [MKAnnotation]) { 
    var annotationsToRemove :[MKAnnotation] = [] 
    var annotationsToAdd: [MKAnnotation] = annotations 
    let annotationsTemp: [MKAnnotation] = annotations 

    for item in mapView.annotations { 
     if item.isKind(of: Cluster.self) { 
      annotationsToRemove.append(item) 
     } else if item.isKind(of: Marker.self) { 
      for itemTemp in annotationsTemp { 
       if itemTemp.coordinate.latitude == item.coordinate.longitude && itemTemp.coordinate.longitude == item.coordinate.longitude { 
        annotationsToAdd.remove(at: annotationsToAdd.index(where: {$0.coordinate.latitude == itemTemp.coordinate.latitude && $0.coordinate.longitude == itemTemp.coordinate.longitude})!) 
       } 
      } 
     } 
    } 
    mapView.removeAnnotations(annotationsToRemove) 
    mapView.addAnnotations(annotationsToAdd) 
} 

func setMapAnnotations(annotations: [MKAnnotation]) { 
    self.mapView.removeAnnotations(self.mapView.annotations) 
    var annotationsToAdd: [MKAnnotation] = [] 
    for item in annotations { 
     if item.isKind(of: Cluster.self) { 
      annotationsToAdd.append(item) 
     } else if item.isKind(of: Marker.self) { 
      annotationsToAdd.append(item) 
     } 
    } 
    DispatchQueue.main.async { 
     self.mapView.addAnnotations(annotationsToAdd) 
    } 
} 

Карта Делегат:

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { 
    if !skipSearchRequest { 
      Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(COHFResultMapViewController.getResultMap), userInfo: nil, repeats: false) 
    } else { 
     skipSearchRequest = false 
    } 

} 

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    if annotation.isKind(of: Cluster.self) { 
     let reuseId = "Cluster" 
     var clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? ClusterView 
     if clusterView == nil { 
      clusterView = ClusterView(annotation: annotation, reuseIdentifier: reuseId) 
     } else { 
      clusterView?.annotation = annotation 
     } 
     return clusterView 
    } else { 
     let reuseId = "Pin" 
     var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) 

     if annotationView == nil { 
      annotationView = AnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     } else { 
      annotationView?.annotation = annotation 
     } 
     return annotationView 
    } 
} 

Как повысить производительность и передовую практику для перезагрузки аннотации в Mapkit? не

Xcode console debugging output

+0

Что означает 'CPU> 100%' означает? –

+0

@NhatDinh При длительной отладке, CPU> 100% и высокой памяти. https://i.stack.imgur.com/tDpIo.png –

+0

Подсказка: вы можете использовать инструменты профилировщика, чтобы найти утечку памяти в коде! –

ответ

0

Вы делаете запрос API на главном потоке, нет-нет.

Вам необходимо запустить запрос API в фоновом потоке, а затем обновить карту в основном потоке. Вроде так:

 
DispatchQueue.global(qos: .userInitiated).async { 
    SearchWebservice.sharedInstance.getResultMap(currentSearchObject, success: { (result) in 

     //process the results 

     //make sure to do any UI/Map stuff back on the main thread 
     DispatchQueue.main.async(execute: { [unowned self] in 
      self.mapView.addAnnotation(marker) 
     }) 

    } 
} 
Смежные вопросы