然后刷新位置 运行 NSXMLParser

Refreshing location then running NSXMLParser

我的应用 (1) 获取用户的位置,然后 (2) 根据该位置数据解析 XML。从负载来看,该应用程序运行良好。但是我想在用户点击刷新按钮时根据位置的变化来更新 XML 。我已经尝试了几个版本,但无法开始工作。我已经包含了我认为与这个问题相关的代码部分(我认为这是一个时间问题)。点击刷新按钮时,位置会更新,但会加载旧的 XML:

class Myclass: UIPageViewController, UIPageViewControllerDataSource, CLLocationManagerDelegate, NSXMLParserDelegate {

    let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    self.dataSource = self
    locationManager.delegate = self

    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.requestWhenInUseAuthorization()
    //locationManager.requestLocation()

}

override func viewWillAppear(animated: Bool) {
    switch CLLocationManager.authorizationStatus() {
    case .AuthorizedWhenInUse, .AuthorizedAlways:
        busyAlertController.display()
        locationManager.requestLocation()
        print("Authorized")
    case .NotDetermined:
        locationManager.requestWhenInUseAuthorization() // or request always if you need it
        print("Not Determined")
    case .Restricted, .Denied:
        print("Restricted or Denied")
        self.dismissViewControllerAnimated(true, completion: nil)
        let alertController = UIAlertController(
            title: "Background Location Access Disabled",
            message: "We need to know your location to show you the correct forecast, please open this app's settings and set location access to 'When in Use' or 'Always'.",
            preferredStyle: .Alert)

        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
        alertController.addAction(cancelAction)

        let openAction = UIAlertAction(title: "Open Settings", style: .Default) { (action) in
            if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
                UIApplication.sharedApplication().openURL(url)
            }
        }
        alertController.addAction(openAction)

        self.presentViewController(alertController, animated: true, completion: nil)
    }

}

// MARK: UIPageViewControllerDataSource & UIPageViewControllerDelegate

// MARK: - CLLocationManagerDelegate

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if (status == .AuthorizedAlways) || (status == .AuthorizedWhenInUse) {
        locationManager.requestLocation()
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {


        let lat =  "\(location.coordinate.latitude)"
        let lon =  "\(location.coordinate.longitude)"


        let url = baseURL + lat + "&lon=" + lon + suffixURL

        guard let urlAsNSURL = NSURL(string: url) else {return}   
        NWSURL = urlAsNSURL
        runParser()


    } else {

       //TODO:

    }
}

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

    print("Error finding location: \(error.localizedDescription)")

    showAlert("Location Problem", message: "We're having trouble finding your location, please try again.")
}

//XMLParser Methods


func parserDidEndDocument(parser: NSXMLParser){

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.showVC()
    })
}


func runParser() {
    guard let url = URL else {

        return}
    guard let parser = NSXMLParser(contentsOfURL: url) else {return}
    parser.delegate = self
    parser.parse()
}


@IBAction func refresh(sender: UIBarButtonItem) {
    locationManager.requestLocation()
    //runParser()
}

}

传递到 locationManager:didUpdateLocations:locations 数组可能包含多个位置,以防更新被推迟或多个位置在交付之前到达。

由于它是按照更新发生的顺序组织的,所以最近的位置更新在数组的末尾。

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  if let location = locations.last {
    ...
  }
}

问题是我没有在 NSXMLParser 完成后清除变量 (array),所以我追加了陈旧的数据,但是因为陈旧的数据是首先它显示在我的 UI 中,并且在我打印到控制台并看到多个数组之前很难检测到问题。我之前做过类似的事情,所以请注意实施 NSXMLParser 的任何人:确保清除用于在 didEndElement 中存储数据的变量。