2016-08-27 3 views
-1

안녕하세요. iOS 용 애플리케이션을 개발 중이며 기능 중 하나는 사용자의 현재 위치를 찾아야합니다. 나는 사용자의 현재 위치를 찾기 위해 노력하고 어디는 FUNC의을 locationManager를 볼 하단에신속하게 사용자의 위치를 ​​찾는 방법은 무엇입니까?

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 



} 
} 

: 여기 내 코드입니다. 이 함수를 시작하여 userLoc을 입력 할 때 앱이 인식하도록하는 방법을 알려주십시오. userLoc은 사용자의 좌표이며 func filterCitysByProximity와 같은 다른 함수에서 사용해야하며 나머지는 코드에서 볼 수 있습니다. 문제의

+0

문제점은 무엇입니까? – Dravidian

답변

0

이유 : -

당신이 CLLocationManager의 대리자를 호출viewDidLoad()에서이 usersCurrent 위치를 검색하는 데 시간이 걸리지 만 usersLocation 당신에게 다시 전달할 수도 전에, 당신의 기능 usersCurrent을 필요로 viewDidLoad()에 전화 했으므로 위치가 표시되어 오류가 발생했습니다.

당신의 코드는 다음과 같이한다 : - : 또한 당신의 didUpdateLocations 경우 기능이

  • 사용자의 위치를 ​​다시 호출되지 않는의 Info.plist 에 Result

    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 description 추가 설정으로 이동하여 서비스 -> 일반 -> 재설정

  • Google을 사용해보십시오, 여러 질문을 찾을 수 있습니다
+0

Readdy 나는 당신에게 그것을 보냈다 – Dakata

+0

나는 일하는 것을 얻었다. 그러나 나는 당신이 여기에서하려고 노력하고 있었던 단 한사람을 이해할 수 없었다. .. 나의 코드를 봐라. – Dravidian

+0

나는 그것을 당신에게 보내었다, 그것을 정말로 감사한다! – Dakata

관련 문제