tezvyn:

Request the user's location one time

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

The Core Location permission and one-shot fetch flow.

OUTLINE

Add a usage description to Info.plist, set a CLLocationManager delegate, request when-in-use authorization, call requestLocation, handle didUpdateLocations and didFailWithError.

WHAT THIS TESTS This verifies you know Core Location's permission gating, the dedicated one-shot API, and the delegate callbacks, plus the privacy plist requirement that trips up beginners.

A GOOD ANSWER COVERS First add a usage-description string to Info.plist, NSLocationWhenInUseUsageDescription, explaining why you need location; without it the system denies access and may crash. Create and retain a CLLocationManager instance, set its delegate to your object conforming to CLLocationManagerDelegate. Call requestWhenInUseAuthorization() to prompt the user. React to the authorization result in the delegate, and once you have when-in-use or always authorization, call requestLocation(), which is purpose-built to deliver a single location fix and then stop. Implement locationManager(_:didUpdateLocations:) to read the most recent CLLocation from the array, and locationManager(_:didFailWithError:) to handle errors like denied or unavailable.

COMMON WRONG ANSWERS Calling requestLocation() before authorization is determined, which fails silently or errors. Forgetting the Info.plist key, the single most common cause of no prompt appearing. Using startUpdatingLocation() and immediately stopping, which is wasteful compared to requestLocation(). Not retaining the manager, so it deallocates before the callback.

LIKELY FOLLOW-UPS The newer locationManagerDidChangeAuthorization(_:) delegate that replaced the deprecated didChangeAuthorization status callback. The difference between when-in-use and always authorization. How requestLocation respects desiredAccuracy and times out. What happens if the user picks the temporary precise-location toggle.

ONE CONCRETE EXAMPLE In your view controller you store let manager = CLLocationManager(), set manager.delegate = self, and call manager.requestWhenInUseAuthorization(). In locationManagerDidChangeAuthorization you check manager.authorizationStatus, and if it is authorizedWhenInUse you call manager.requestLocation(). The system delivers locationManager(_:didUpdateLocations:) with one CLLocation; you read locations.last.coordinate and use it. If the user denied access, didFailWithError fires and you show a message guiding them to Settings.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.