【问题标题】:MapKit annotations only show after a delay in foreground (or going to Home screen and back)MapKit 注释仅在前景延迟后显示(或进入主屏幕并返回)
【发布时间】:2026-02-17 00:20:04
【问题描述】:

我正在从服务器加载一组自定义注释,并希望使用以下代码将它们添加到地图中。注释仅在应用程序处于前台 10 秒左右后才会出现在地图上。但是,当我转到主屏幕(应用程序在后台)然后返回应用程序时,它们会立即出现。 当应用程序在前台时,如何让这些注释立即显示?

我从服务器获取自定义注释数组并尝试将它们添加到地图中,如下所示:

if UIApplication.sharedApplication().applicationState == .Active {
self.myMap.showAnnotations(self.these_new_pins, animated: true)
}

我的 mapView viewForAnnotation 看起来像这样:

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {

if !(annotation is CustomPointAnnotation) {
                return nil
            }

            // ... otherwise continue executing function
            var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier("pin")

            if pinView == nil {
                pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
                pinView!.canShowCallout = true
                pinView!.alpha = 0.97
                pinView!.centerOffset.y = -23

            }

            else {

                pinView!.annotation = annotation
            }


            let cpa = annotation as! CustomPointAnnotation

            // Pin color varies (user green, server blue)
                pinView!.image = UIImage(named: cpa.pin_image)

            // Add detail button to right callout
                var calloutButton = UIButton.buttonWithType(.System) as! UIButton
                var btnimage = UIImage(named: cpa.pin_btnimage)!

                    calloutButton.frame = CGRectMake(0, 0, 30, 30)
                    calloutButton.setBackgroundImage(btnimage, forState: UIControlState.Normal)

                pinView!.rightCalloutAccessoryView = calloutButton

            // Add detail button to left callout
                var optionsButton = UIButton.buttonWithType(.System) as! UIButton
                var btnimage_options = UIImage(named: cpa.pin_btnimage_options)

                    optionsButton.frame = CGRectMake(0, 0, 30, 30)
                    optionsButton.setBackgroundImage(btnimage_options, forState: UIControlState.Normal)

                pinView!.leftCalloutAccessoryView = optionsButton


            return pinView
        }

谢谢!

【问题讨论】:

  • 嗨。看起来你不是从主线程调用“showAnnotations”。
  • 在 Mozilla 上的现货!这解决了它! dispatch_async(dispatch_get_main_queue()) { if UIApplication.sharedApplication().applicationState == .Active { self.myMap.showAnnotations(self.these_new_pins, animated: true) } }

标签: ios swift annotations mapkit foreground


【解决方案1】:

答案是从主线程调用 showAnnotations(感谢 Mozilla)。这是执行此操作的代码:

dispatch_async(dispatch_get_main_queue()) { if UIApplication.sharedApplication().applicationState == .Active { self.myMap.showAnnotations(self.these_new_pins, animated: true) } } 

【讨论】:

    最近更新 更多