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

标签 swift ios8 core-location xcode6.3 clgeocoder

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

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.
    }

}

最佳答案

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

解决方案:

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

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

关于swift - 如何在 Swift viewDidLoad 中获取邮政编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31095881/

相关文章:

ios - 自定义 UITableViewCell 中的按钮 Segue

ios - @3x 图像在 XIB 中的 iPhone 6 或 5S 或 5 上错误地使用了 "Use as Launch Image"选项集

swift - 如何更改导航栏标题位置?

ios - UIVibrancyEffect 在设备上变暗,在模拟器中充满活力

objective-c - didStartMonitoringForRegion 一次调用两次 startMonitoringForRegion

ios - 收藏 View 作为自定义键盘不起作用

ios - 具有非标准化数据的 Realm 迁移

iphone - 核心位置第一点无效

ios - 如何初始化和自定义 GMSPlace 对象

swift - 如何使用 swift 设置/访问 Collection View 的标签值