如果语句没有改变全局变量swift

时间:2017-05-09 21:31:00

标签: ios swift clgeocoder

我正在尝试设置一个函数来获取app委托中的当前位置,但是当我在底部的print(city)时,它返回全局变量中的原始初始化值“hello”,即使我更新了CLGeocoder下的值。

AppDelegate:

    import UIKit
    import CoreData
    import CoreLocation

    let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    var country = "hello"
    var city = "hello"

 func setupLocationManager(){
        let locationManager = CLLocationManager()
        locationManager.requestAlwaysAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }

    // Below method will provide you current location.
    func getLocation() -> [String]{
        let manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

        let selflocation = manager.location

        let latitude: Double = selflocation!.coordinate.latitude
        let longitude: Double = selflocation!.coordinate.longitude


        print("current latitude :: \(latitude)")
        print("current longitude :: \(longitude)")

        let location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!            

        CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
            print(location)

            if error != nil {
                print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
            }

            let pm = placemarks![0]
            let speed = (selflocation?.speed)!
            city = pm.addressDictionary!["City"]! as! String
            country = pm.addressDictionary!["Country"]! as! String

            if (placemarks?.count)! > 0 {
            }
            else {
                print("Problem with the data received from geocoder")
            }
        })

        print(city)
        return [city as! String, country as! String]
    }

4 个答案:

答案 0 :(得分:1)

这是因为地理编码是异步完成的,因此在地理编码完成之前正在执行print(city)。所以我建议你这样做。

func getLocation(completion: @escaping (Array<String>)->()){

    let manager = CLLocationManager()

    manager.desiredAccuracy = kCLLocationAccuracyBest

    manager.requestAlwaysAuthorization()

    manager.startUpdatingLocation()

    let selflocation = manager.location

    let latitude: Double = selflocation!.coordinate.latitude

    let longitude: Double = selflocation!.coordinate.longitude

    let location = CLLocation(latitude: latitude, longitude: longitude)

    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in

        if let error = error {

            print(error.localizedDescription)

            return
        }

        if let placemark = placemarks?.first {

            if let country = placemark.country, let city = placemark.locality {

                completion([city, country])

                return

            } else {

                print("country or city was nil.")
            }
        } else {

            print("Problem with the data received from geocoder")
        }
    })
}

所以不要拨打getLocation()来电话

getLocation { (location) in

    print(location)
}

答案 1 :(得分:1)

此处的问题是您在为其分配新位置值之前获取该值。你必须等一下才能获得更新的值。

答案 2 :(得分:0)

reverseGeocodeLocation异步工作,因此print语句实际上在它完成之前发生。如果您有任何依赖于结果的逻辑,您可能需要将其置于完成处理程序闭包中。

答案 3 :(得分:0)

与其他答案一样,reverseGeocodeLocation异步工作,因此您可能希望在闭包内移动print(city),例如在

之后
else {
    print("Problem with the data received from geocoder")
}