UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Getting a location then running code once location has been found

Forums > Swift

Hello

I'm trying to challenge myself by building a Bus times app for iOS devices. The basic idea is that when the app opens it grabs your location then queries a JSON API to find the nearest bus stop then loads the departures for that stop. Eventually, I would like to make it an iOS 14 widget but that's a future target.

So far I've got the app loading the departures for one bus stop but its time to make it a bit smarter and let it find a stop based on the device's location (it's currently just hardcoded to load up departures from one stop).

The problem I'm running into is that while I can start location services and get it searching for a location when I try to get a location its nil. So if I'm understanding things right it is eventually getting the location but its running all the rest of my code before it gets a location so when my code is trying to use the location its nil.

So can anybody point me in the right direction to how do I get code to execute only after a location has been found?

I hope I've explained this well enough and thanks for reading.

2      

Hi, it is a bit difficult but I suspect you are treating location search as synchronous code which means you expect the lines to execute one by one.

But this operation is asynchronous, which means you start it, then the rest of the synchronous code runs and then the location search finishes so that is why you are getting a nil back. You need to use delegate methods for callback and start your API query there.

So you need something like this:

func locationManager(_ manager: CLLocationManager,  didUpdateLocations locations: [CLLocation]) {
    let lastLocation = locations.last!

    // query API here with the location you just got
}

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.