139

I am using google maps in Xcode 9 beta, iOS 11.

I am getting an error outputted to the log as follows:

Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState] PID: 4442, TID: 837820, Thread name: com.google.Maps.LabelingBehavior, Queue name: com.apple.root.default-qos.overcommit, QoS: 21

Why would this be occurring as I am almost certain I'm not altering any interface elements from the main thread in my code.

 override func viewDidLoad() {

    let locationManager = CLLocationManager()


    locationManager.requestAlwaysAuthorization()


    locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {

            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }

      viewMap.delegate = self

     let camera = GMSCameraPosition.camera(withLatitude: 53.7931183329367, longitude: -1.53649874031544, zoom: 17.0)


        viewMap.animate(to: camera)


    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }

    func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {


    }

    func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {

        if(moving > 1){
            moving = 1
        UIView.animate(withDuration: 0.5, delay: 0, animations: {

            self.topBarConstraint.constant = self.topBarConstraint.constant + (self.topBar.bounds.height / 2)

            self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant + (self.topBar.bounds.height / 2)

            self.view.layoutIfNeeded()
        }, completion: nil)
    }
         moving = 1
    }


    // Camera change Position this methods will call every time
    func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
        moving = moving + 1
        if(moving == 2){


            UIView.animate(withDuration: 0.5, delay: 0, animations: {


                self.topBarConstraint.constant = self.topBarConstraint.constant - (self.topBar.bounds.height / 2)

                self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant - (self.topBar.bounds.height / 2)


                self.view.layoutIfNeeded()
            }, completion: nil)
        }
        DispatchQueue.main.async {

            print("Moving: \(moving) Latitude: \(self.viewMap.camera.target.latitude)")
            print("Moving: \(moving)  Longitude: \(self.viewMap.camera.target.longitude)")
        }
    }
9
  • 2
    In mapView(_:didChange) you are dispatching the print statements to the main queue. Are you not already on the main queue? If not, you have to dispatch the animate call to the main queue, too. I'd suggest inserting a few dispatchPrecondition(condition: .onQueue(.main)) before those UI updates, just to make sure.
    – Rob
    Commented Jun 26, 2017 at 20:50
  • You said "I am almost certain I'm not altering any interface elements from the main thread in my code." I assume you meant "...from any background thread."
    – Rob
    Commented Jun 26, 2017 at 20:51
  • 2
    Not your issue. I thing it is at their end. It stops in "com.google.Maps.LabelingBehavior". I have the same poblem. Commented Jun 26, 2017 at 21:59
  • 2
    Hi, yes it did, the issue seems to lie with google, hopefully they will release an updated version soon
    – MattBlack
    Commented Aug 29, 2017 at 12:44
  • 1
    @MattBlack Take a look at this answer: stackoverflow.com/a/44392584/5912335 Commented Sep 21, 2017 at 22:07

4 Answers 4

184

It's hard to find the UI code which is not executed in main thread sometimes. You can use the trick below to locate it and fix it.

  1. Choose Edit Scheme -> Diagnostics, tick Main Thread Checker.

    Xcode 11.4.1

    Click the small arrow next to the Main Thread Checker to create a Main Thread Checker breakpoint. enter image description here

    Previous Xcode

    Tick on Pause on issues. enter image description here

  2. Run your iOS application to reproduce this issue. (Xcode should pause on the first issue.) enter image description here

  3. Wrap the code that modify the UI in DispatchQueue.main.async {} enter image description here

9
  • 11
    For some reason, when I do that in Xcode 10.1, I only get a callstack that is helpless and that I cannot relate to a code line: 2018-12-29 19:46:56.500629+0100 BedtimePrototype[1553:834478] [reports] Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState] PID: 1553, TID: 834478, Thread name: com.apple.CoreMotion.MotionThread, Queue name: com.apple.root.default-qos.overcommit, QoS: 0
    – Vilmir
    Commented Dec 29, 2018 at 18:51
  • 1
    I also got a call stack that look helpless. On left hand side it stopped at "com.apple.CoreMotion.MotionThread(23)", then I check all other threads as well. In Thread 1 something caught my attention: it is SVProgressHUD (a progress view library I used). So, I know it's a call to SVProgressHUD.show() somewhere in target view controller. Then either wrap each appearance with DispatchQueue.main.async or simply comment out, test again and I found out which one is problematic.
    – John Pang
    Commented Feb 20, 2019 at 14:22
  • 2
    I also got rid of the warning by commenting out SVProgressHUD.show. Wrapping this call into a DispatchQueue.main.async did not get rid of the warning. I use the pod in v2.2.5 This thread can help understanding the problem better: github.com/SVProgressHUD/SVProgressHUD/issues/950
    – Vilmir
    Commented Apr 20, 2019 at 19:30
  • 2
    The "Pause on Issues" checkbox isn't there for me in xcode 11.4.1. Edit: I found a small arrow next to the Main Thread Checker. Clicking that adds a breakpoint for you.
    – ChrisO
    Commented May 19, 2020 at 14:04
  • 3
    This appears to have disappeared in Xcode 12. Does anyone know where it moved?
    – below
    Commented Sep 30, 2020 at 15:36
91

First, make sure your invocations of google maps and ui changes are called from the main thread.

You can enable Thread Sanitizer option in Xcode using below steps:

Screenshot

You can put offending lines on the main thread with the following:

DispatchQueue.main.async {
    //Do UI Code here. 
    //Call Google maps methods.
}

Also, update your current version of google maps. Google maps had to make a couple of updates for the thread checker.

For the question: "Why would this be occurring?" I think Apple added an assertion for an edge case which Google then had to update their pod for.

8
  • 1
    @thibautnoah, are you saying that because I did not phrase it as "it (the problem) is occuring because you are using xcode 9 beta in combination with Google's API?" Or because you are facing a similar bug which is not solved by my answer? Commented Sep 4, 2017 at 10:42
  • 7
    Xcode 9 highlighted some threading issues which xcode 8 apparently does not detect (whether it is due to xcode settings or another thing is to be determined). Switching back to xcode 8 is equivalent to ignoring your threading issues, they are still there and are not solved, thus it is not a solution, you are just burying your head in the sand and pretending everything is ok. If the issue is coming from a framework please submit an issue so that it can be fixed. Commented Sep 4, 2017 at 12:01
  • Xcode 9 detects threading issues which xcode 8 does not proport to detect, AND Xcode 9 in combination with Google's API likely does cause this bug. This bug is sited in the debugger for multiple crashes AND the crashes no longer happen when you switch back to xcode 8. Commented Sep 4, 2017 at 18:34
  • You're point is that the thread checker is showing the symptom not the cause. I'm saying Xcode 9 beta is both the cause AND the symptom communicator. "the crashes no longer happen when you switch back to xcode 8". There is a difference between XCode warnings and actual crashes with debugger readouts. This error can show up as a warning OR a crash. The crashing goes away entirely when switching back to xcode 8. Xcode 9 beta is called beta for a good reason. Commented Sep 5, 2017 at 8:10
  • 2
    Yes...I think its hard for many ios developers to see that just because something is showing the symptom, doesn't mean it is gauranteed not to be the the cause as well. I think its also hard to accept that Apple might have ever made a mistake. Commented Sep 20, 2017 at 18:35
57

Wrap the lines of code that modify the UI in DispatchQueue.main.async {} in order to make sure they execute on the main thread. Otherwise, you may be calling them from a background thread, where UI modifications are not allowed. All such lines of code must be executed from the main thread.

4
  • 4
    yes I have already used that but the warning is still present
    – MattBlack
    Commented Jul 6, 2017 at 8:24
  • @Pang, it's used for printing things, not for the main UI code.
    – Toma
    Commented Jul 6, 2017 at 12:37
  • 4
    @MattBlack try to wrap all things that modify the UI on the DispatchQueue.main.async {}
    – Toma
    Commented Jul 6, 2017 at 12:38
  • 1
    @user6603599-Works like a charm
    – IOSDevops
    Commented Jan 3, 2018 at 21:25
-46

Choose scheme -> Diagnotics, remove main thread checker, then the warning will disappear. scheme editor

5
  • 22
    I don't think this is a good idea. There is a problem here that the thread checker has discovered. Disabling thread checker will allow this and future problems to go undiscovered, and cause future technical debt to be incurred fixing the issues.
    – ablarg
    Commented Aug 25, 2017 at 19:19
  • 1
    Actually, my point is we can do this when we use OpenGL es rendering, because we can't render frame buffer in main thread. right?
    – L.Peng
    Commented Aug 29, 2017 at 12:50
  • 3
    Ah, so if the waring doesn't appear the problem doesn't exists? Commented Nov 24, 2017 at 13:26
  • 18
    "Why does my smoke detector keep going off?" "Just remove the battery, problem solved." Commented Oct 4, 2018 at 18:52
  • If the warning doesn't appear the problem doesn't exists?
    – S. Gissel
    Commented Jan 6, 2020 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.