2016-08-27 32 views
-1

你好我正在開發一個應用程序的ios和它的一個功能必須找到用戶的當前位置。這裏是我的代碼:如何在swift中查找用戶的位置?

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)中使用它們,剩下的部分可以在代碼中看到。

+0

什麼問題? – Dravidian

回答

0

原因,您的問題: -

當你調用CLLocationManager的代表viewDidLoad()它需要一些時間來檢索usersCurrent位置,但即使之前usersLocation可以轉發回給你,你的功能要求usersCurrent正如您在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功能不被調用

  • 重置您的位置服務通過進入設置 - >常規 - >重置
  • 嘗試谷歌,你會發現有多個問題
+0

Readdy我把它寄給你 – Dakata

+0

我得到它的工作,但我不明白你在這裏試圖做的一件事...看看我的代碼 – Dravidian

+0

我發送了你,請檢查它,非常感謝! – Dakata

相關問題