即使之前调用了函数,函数也会在代码块之后运行

时间:2016-06-15 19:52:15

标签: ios swift

好的,我没有得到这个。我已经编写了一些前向地理编码的代码,我有一个UITextField,您可以在其中输入一个城市的名称,然后在按下Enter按钮后将其解除,同时调用该函数以确定UITextField是否包含有效输入。如果有错误,则将其保存在bool变量中,该变量在函数中更改。我到处都有打印语句,从控制台输出我可以看到该函数在if条件之后运行,但之前调用它...什么?有人可以解释一下发生了什么吗?代码:

var locationError: Bool?

func textFieldShouldReturn(textField: UITextField) -> Bool {
    self.view.endEditing(true)

    forwardGeocoding(textField.text!)
    print("forward geocoding ran 1st time")

    print(locationError)
    if locationError == true {
        print("Error")
    } else if locationError == false {
        print("Success")
    } else if locationError == nil {
        print("No value for locationError")
    }

    return false
}

func forwardGeocoding(address: String) -> CLLocation? {
    var userLocation: CLLocation?
    CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
        if error != nil {
            print("Geocoding error: \(error)") 
            self.locationError = true
            return
        }
        if placemarks?.count > 0 {
            print("Placemark found")
            self.locationError = false
            let placemark = placemarks?.first
            let location = placemark?.location
            let coordinate = location?.coordinate
            print("Settings location: \(coordinate!.latitude), \(coordinate!.longitude)")
            if let unwrappedCoordinate = coordinate {
                let CLReadyLocation: CLLocation = CLLocation(latitude: unwrappedCoordinate.latitude, longitude: unwrappedCoordinate.longitude)
                userLocation = CLReadyLocation
            }
        }
    })
    return userLocation
}

控制台输出:

forward geocoding ran 1st time
nil
No value for locationError
Placemark found
Settings location: 48.8567879, 2.3510768

3 个答案:

答案 0 :(得分:0)

尝试多线程...

let queue = NSOperationQueue()
    queue.addOperationWithBlock() {
          NSOperationQueue.mainQueue().addOperationWithBlock() {
    }
}

答案 1 :(得分:0)

您需要添加完成处理程序作为函数参数:

func forwardGeocoding(address: String, completionHandler: (placemarks: String? or [Array of any type], error: NSError?) -> ()) -> CLLocation?

修改你的if块:

if error != nil {
            print("Geocoding error: \(error)") 
            self.locationError = true
            completionHandler(nil, error)
            return
        }

然后将其称为

forwardGeocoding(textField.text!){(placemarks, error) in
//your code.

}

答案 2 :(得分:0)

当你致电geocodeAddressString时,它会在一个单独的线程中执行(#AppleDoc This method submits the specified location data to the geocoding server asynchronously and returns)。所以有效地你有两个并行运行的线程。线程2中的geocodeAddressString将花费更多时间来执行,因为它会进行服务器调用,并且在调用返回时将执行该块。在此期间,线程1将完成其执行并将打印日志语句。

如果你想处理这个问题,应该以执行回调后触发的方式实现locationError if-else条件逻辑。