正在刷新位置,然后运行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中存储数据的变量。

相关内容

最新更新