如何在Swift viewDidLoad中获取邮政编码?

时间:2015-06-28 03:32:46

标签: swift ios8 core-location xcode6.3 clgeocoder

我是Swift的新手,我需要在var postalCode中设置viewDidLoad()。正如您在下面的代码中看到的,我在didUpdateLocations中使用了反向地理编码位置,但由于它是异步的,postalCode变量未在viewDidLoad()中设置。我怎么能这样做?

ViewController.swift

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    var postalCode = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        println("Postal code is: \(self.postalCode)")
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)-> Void in
            if error != nil {
                println("Reverse geocoder failed with error: \(error.localizedDescription)")
                return
            }

            if placemarks.count > 0 {
                let placemark = placemarks[0] as! CLPlacemark
                self.locationManager.stopUpdatingLocation()
                self.postalCode = (placemark.postalCode != nil) ? placemark.postalCode : ""
                println("Postal code updated to: \(self.postalCode)")
            }else{
                println("No placemarks found.")
            }
        })
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println("Location manager error: \(error.localizedDescription)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

2 个答案:

答案 0 :(得分:0)

实际上有两个连续的异步操作。首先是位置更新,然后是地理编码。您不希望等待viewDidLoad()中的结果,因为它会导致糟糕的用户体验,并且可能iOS甚至会将应用程序从内存中逐出而无法响应。

更改应用程序逻辑,以便在ZIP可用时使用它。例如,如果要在UI中显示ZIP,请在启动时将其留空,并从reverseGeocodeLocation完成处理程序更新它。它会在可用时立即显示。

答案 1 :(得分:0)

@MirekE是正确的。您的-viewDidLoad方法不会等待位置管理员完成更新,然后让地理编码器完成地理编码。在设置Postal code is:的值之前,它会记录消息postalCode

<强>解决方案:

将您需要的任何代码移到didSet上的自定义postalCode触发器中:

var postalCode:String! = "" {
    didSet {
        println("Postal code is: \(self.postalCode)")
        // and whatever other code you need here.
    }
};