locationManager 函数在代码结束时触发

locationManager function triggered at end of code

我试图让我的代码获取用户的当前位置并将其发送到服务器。当我 运行 我的代码时, LocationManager 函数似乎只在我的 startload 函数中的所有内容都完成后才会触发。我试图在 将数据发送到服务器之前 获取用户的位置。

class ViewController: .....
    var currentLoc = "0"
    [...]
    func startload(place: String){ // Starts the process, send recording data and location to node
            // GETS LOCATION
            print(place)
            locationManager.requestWhenInUseAuthorization()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestLocation()
            print("Just req location")
            // GETS LOCATION
            // SENDS REQUEST
            // create the request & response
            let request = NSMutableURLRequest(URL: NSURL(string: "https://4890adf2.ngrok.io/ios")!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
            var response: NSURLResponse?

            // create some JSON data and configure the request
            print("preping json")
            let jsonString = "json={\"location\":\"\(currentLoc)\", \"Place\": \" \(place) \"}"
            request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
            request.HTTPMethod = "POST"
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

            // send the request
            print("Sending the request")
            do{
                let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
                let datastring = NSString(data: data, encoding:NSUTF8StringEncoding)
                print("Datastring: \(datastring!)")
            } catch let error {
                print(error)
            }
            // look at the response
            //print("The response: \(response)")
            if let httpResponse = response as? NSHTTPURLResponse {
                print("HTTP response: \(httpResponse.statusCode)")
            } else {
                print("No HTTP response")
            }
            // SENDS REQUEST
        }

        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            print("Inside LocationManager")
            if let location = locations.first {
                currentLoc = String(location)
            } else {
                // ...
            }
        }

        func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
            print("Error finding location: \(error.localizedDescription)")
        }

我尝试在 locationManager.requestLocation() 之后添加 sleep() 以查看是否可以尝试停止执行直到 locationManager 函数被触发,但即使在休眠时它仍然不会触发器。

控制台输出如下:

First hit
restaurant
Just req location
preping json
Sending the request
Datastring: HTTP 200
HTTP response: 200
Inside LocationManager

我想你弄错了。 LocationManager 是一个异步 API,一旦委托方法有消息要告诉您,您就可以回调它。

不要按顺序编写程序,以为它会立即为您提供数据。

根据 iOS 的 LocationManager 实施调整您的代码,并将您的服务器调用移至 didUpdateLocations API。 请注意,此方法会根据位置变化被多次调用,因此,您可能需要仔细检查要发送到服务器的时间和数据。