ios - 刷新位置然后运行 ​​NSXMLParser

标签 ios swift core-location 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 {
    ...
  }
}

关于ios - 刷新位置然后运行 ​​NSXMLParser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977055/

相关文章:

ios - 在独立的 UINavigationBar 上应用栏指标

swift - 快速解析使用(Tableview)

ios - 如何推迟【权限请求提醒】?

ios - CLLocationManager 未确定位置

ios - 从给定坐标(不是当前位置,而是手动提供)进行反向地理编码

ios - NSLocation 不等我点击允许

ios - 如何在 swift 中初始化 Custom UITableViewCell 的不同属性

javascript - CSS 的 iOS Safari 滚动问题

ios9应用程序传输安全问题在模拟器和设备中不同

ios - iOS:打开具有已填充日期的“日历”应用“新事件”屏幕