我正在尝试获取代码以提取用户的当前位置并将其发送到服务器。当我运行代码时,似乎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)")
        }


我尝试在sleep()之后添加locationManager.requestLocation()来查看是否可以尝试停止执行,直到触发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中移动服务器调用。当心,此方法会根据位置更改多次调用,因此,您可能需要仔细检查要何时将什么数据发送到服务器。

关于swift - 在代码末尾触发locationManager函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33325334/

10-13 02:37