Xcode warning when using MapKit and CoreLocation

安稳与你 提交于 2019-11-27 16:24:16

You are calling requestWhenInUseAuthorization, that is true. But are you waiting until you get authorization? No, you are not. You (as the user) are tapping Allow, but that's happening too late: your code has already continued, going straight on to tell the map view to start tracking the user's location.

Just look at the docs on requestWhenInUseAuthorization:

When the current authorization status is kCLAuthorizationStatusNotDetermined, this method runs asynchronously

Get that? Runs asynchronously. That means that asking for permission happens in the background on another thread.

And the docs go on to say:

After the status is determined, the location manager delivers the results to the delegate’s locationManager:didChangeAuthorizationStatus: method

So, implement that method. If you have just obtained permission, that is the signal that you can start using the location manager.

Also, you are missing an important step: you are not checking what the status actually is. You should only be asking for authorization if the status is undetermined. If the status is restricted or denied, you must not use the location manager at all; and if the status is granted, there is no point asking for authorization again.

So, just to sum up, your logical flowchart should be:

  • Check status.

  • Is the status Restricted or Denied? Stop. You cannot use get location updates or do location on a map.

  • Is the status Granted? Proceed to get location updates or do location on a map.

  • Is the status Undetermined? Request authorization and stop. Treat locationManager:didChangeAuthorizationStatus: as the completion handler for your authorization request. At that point, go back to start of the flowchart!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!