-->

How To Tell If User Is At A Specific Location?

2019-06-09 00:13发布

问题:

Essentially what I need to do is find out if a user is at a specific place (IE at a venue). And if the user is, allow access to a specific ViewController.

I've been looking high and low for an answer to this problem online and surprisingly I haven't found anything. I will say I'm pretty new to iOS development.

I don't need anything as complex as geofencing like in the Ray Wenderlich tutorial, and I don't need to run it in the background. I also don't need to know if they entered or left. Just whether or not they are within that area or not when the user clicks a button.

I've gotten as far as being able to get the users location using CoreLocation, but I'm confused as to how I will go about identifying if the user is at the specific location. Ideally, I will want a radius of about 5 miles (It's a big location).

回答1:

if you have the user's location as well as the venue's location you can do the following:

let radius: Double = 5 // miles

let userLocation = CLLocation(latitude: 51.499336, longitude: -0.187390)
let venueLocation = CLLocation(latitude: 51.500909, longitude: -0.177366)

let distanceInMeters = userLocation.distanceFromLocation(venueLocation)
let distanceInMiles = distanceInMeters * 0.00062137

if distanceInMiles < radius {
    // user is near the venue
}


回答2:

If you have the latitude and longitude of the venue, just create a CLLocation object for that and see how far the user is from that location.

// get the current user location, then...

let MinDistance = 100.0 // meters
let distance = venueLocation.distanceFromLocation(userLocation)
if distance < MinDistance {
    // I'm close enough to the venue!
}