如何在swift中找到用户的位置?

时间:2016-08-27 13:28:06

标签: swift location cllocation

您好我正在为ios开发一个应用程序,其中一个功能必须找到用户的当前位置。这是我的代码:

 import UIKit
 import MapKit
 import CoreLocation
 import SwiftyJSON

 struct City {
let name : String
let location : CLLocation
let description :String
let imageName : String

func distanceTo(location:CLLocation) -> Int
{
    let distanceMeters = location.distanceFromLocation(self.location)
    let distanceKilometers = distanceMeters / 1000.00
    return Int(round(100 * distanceKilometers) / 100)
}
}

class FirstViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var LabelTest: UILabel!
@IBOutlet weak var Slider: UISlider!
@IBOutlet weak var LabelValueSlider: UILabel!
var MySliderCurrentValue = Double()

var manager = CLLocationManager()

var userLoc: CLLocationCoordinate2D!


{
    willSet{
        self.orderCitysByProximity()
        self.filterCitysByProximity(Int(self.Slider.value))
        self.LocateMe(manager)

    }
}
var cities = [City]()
var nearbyCities = [City]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let path: String = NSBundle.mainBundle().pathForResource("cities", ofType: "json") as String!
    let jsonData = NSData(contentsOfFile: path) as NSData!
    //let ReadableJSON = JSON ( data:jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil )

    do {
        let jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
        for city in jsonObject["cities"] as! [[String:AnyObject]] {
            //let coordinates = position["Position"] as! [String:CLLocationDegrees]
            let cityName = city["Name"] as! String
            let latitude = city["Latitude"] as! Double
            let longitude = city["Longitude"] as! Double
            let description = city["Description"] as! String
            let image = city["Image"] as! String
            let location = CLLocation(latitude: latitude, longitude: longitude)
            let city = City(name: cityName, location: location,description: description, imageName: image)
            cities.append(city)
            // print(cities)
        }


        self.orderCitysByProximity()
       self.filterCitysByProximity(Int(self.Slider.value))


    } catch let error as NSError {
        print(error)
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func SliderChange(sender: UISlider) {
    let MySliderCurrentValue: String = String(Int(sender.value))
    LabelValueSlider.text = MySliderCurrentValue
    self.filterCitysByProximity(Int(sender.value))
}

@IBAction func goToTableView()
{
   if let tableViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tableViewController") as? TableViewController
   {
        tableViewController.cities = self.nearbyCities
        self.navigationController?.pushViewController(tableViewController, animated: true)
    }
}


func filterCitysByProximity(kilometers:Int)
{
    self.nearbyCities.removeAll()
    for city in self.cities {
        if(city.distanceTo(self.userLoc) <= kilometers*2)
        {
            self.nearbyCities.append(city)
        }
    }

    self.LabelTest.text = "you have \(self.nearbyCities.count) cities nearby"
   let OrderedArray = self.nearbyCities.sort({ $0.distanceTo(self.userLoc) < $1.distanceTo(self.userLoc) })
   self.nearbyCities = OrderedArray
}

func orderCitysByProximity()
{
    let OrderedArray = self.cities.sort({ $0.distanceTo(self.userLoc) < $1.distanceTo(self.userLoc) })
    self.cities = OrderedArray
}

@IBAction func LocateMe(sender: AnyObject) {
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

}
func  locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userlocation: CLLocation = locations[0] as CLLocation
    manager.stopUpdatingLocation()
    let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
    self.userLoc = location



}
}

在底部,您将看到func locationManager,我正在尝试查找用户的当前位置。您能告诉我如何启动此功能,以便应用程序识别我何时键入userLoc。 userLoc是用户的协调,我必须在其他函数中使用它们,例如func filterCitysByProximity,以及其他函数,您可以在代码中看到它们。

1 个答案:

答案 0 :(得分:0)

您遇到问题的原因: -

当您在viewDidLoad()中调用 CLLocationManager 的委托时,需要一些时间来检索usersCurrent Location,但即使在usersLocation可以转发给您之前,您需要usersCurrent Location的函数也是如此。因为你在viewDidLoad()中调用它们而被触发,从而导致错误!

您的代码应如下所示: -

import UIKit
import MapKit
import CoreLocation
import SwiftyJSON

struct City {
let name : String
let location : CLLocation
let description :String
let imageName : String

func distanceTo(location:CLLocation) -> Int
{
    let distanceMeters = location.distanceFromLocation(self.location)
    let distanceKilometers = distanceMeters / 1000.00
    return Int(round(100 * distanceKilometers) / 100)
}
}

class FirstViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var LabelTest: UILabel!
@IBOutlet weak var Slider: UISlider!
@IBOutlet weak var LabelValueSlider: UILabel!
var MySliderCurrentValue = Double()

var locationManager = CLLocationManager()

var userLoc : CLLocation!
var cities = [City]()
var nearbyCities = [City]()



override func viewDidLoad() {

    super.viewDidLoad()



    let path: String = NSBundle.mainBundle().pathForResource("cities", ofType: "json") as String!
    let jsonData = NSData(contentsOfFile: path) as NSData!
    do {
        let jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
        for city in jsonObject["cities"] as! [[String:AnyObject]] {
            //let coordinates = position["Position"] as! [String:CLLocationDegrees]
            let cityName = city["Name"] as! String
            let latitude = city["Latitude"] as! Double
            let longitude = city["Longitude"] as! Double
            let description = city["Description"] as! String
            let image = city["Image"] as! String
            let location = CLLocation(latitude: latitude, longitude: longitude)
            let city = City(name: cityName, location: location,description: description, imageName: image)
            cities.append(city)

        }

    } catch let error as NSError {
        print(error)
    }


    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.requestWhenInUseAuthorization()
    locationManager.startMonitoringSignificantLocationChanges()
    locationManager.startUpdatingLocation()

            if locationManager.respondsToSelector(#selector(locationManager.requestWhenInUseAuthorization)) {
                locationManager.requestWhenInUseAuthorization()
                locationManager.requestLocation()
            }
            else {
                locationManager.startUpdatingLocation()
            }


}


@IBAction func SliderChange(sender: UISlider) {
    let MySliderCurrentValue: String = String(Int(sender.value))
    LabelValueSlider.text = MySliderCurrentValue
    if userLoc != nil{
       self.filterCitysByProximity(Int(sender.value), location: userLoc)
    }else{
        let alertC : UIAlertController = UIAlertController(title: "Iwin", message: "UserLocation Not Updated wait a while", preferredStyle: .Alert)
        let okAction : UIAlertAction = UIAlertAction(title: "oK", style: .Default, handler: { (okActn) in
            print("User pressed ok")
        })
        alertC.addAction(okAction)
        alertC.popoverPresentationController?.sourceView = view
        alertC.popoverPresentationController?.sourceRect = view.frame
        self.presentViewController(alertC, animated: true, completion: nil)
    }
}


//Segue to .. :-


@IBAction func goToTableView()
{
   if let tableViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tableViewController") as? TableViewController
   {
        tableViewController.cities = self.nearbyCities
        print(nearbyCities)
        self.navigationController?.pushViewController(tableViewController, animated: true)
    }
}

     @IBAction func LocateMe(sender: AnyObject) {

}





//Class Functions call :-





func filterCitysByProximity(kilometers:Int, location: CLLocation)
{
    self.nearbyCities.removeAll()
    for city in self.cities {
        if(city.distanceTo(location) <= kilometers*2)
        {
            self.nearbyCities.append(city)
        }
    }

    self.LabelTest.text = "you have \(self.nearbyCities.count) cities nearby"
    let OrderedArray = self.nearbyCities.sort({ $0.distanceTo(location) < $1.distanceTo(location) })
    self.nearbyCities = OrderedArray
}

func orderCitysByProximity(location: CLLocation)
{
    let OrderedArray = self.cities.sort({ $0.distanceTo(location) < $1.distanceTo(location) })
    self.cities = OrderedArray
}




//Location Manager Functions :-



func  locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    userLoc = locations[0] as CLLocation
    locationManager.stopUpdatingLocation()
    print(userLoc)
    self.orderCitysByProximity(userLoc)
    self.filterCitysByProximity(Int(self.Slider.value), location : userLoc)

}


func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

    if status == .AuthorizedWhenInUse {

        print("authorised call came . . . . ")
        locationManager.startUpdatingLocation()
    }
}


func locationManager(manager: CLLocationManager, didFailWithError error: NSError){


print(error.localizedDescription)
locationManager.stopUpdatingLocation()
}


}

privacy - location usage descriptionResult添加到您的info.plist 此外,如果您的 didUpdateLocations 功能未被调用

  • 通过进入设置重置您的位置服务 - >常规 - >重置
  • 试试谷歌,你会发现多个问题