在代码

时间:2015-10-25 01:50:15

标签: swift ios9 core-location locationmanager

我试图让我的代码拿起用户的当前位置并将其发送到服务器。当我运行我的代码时,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功能被解雇,但即使在睡觉时它仍然没有&#39} ; t触发器。

控制台输出如下:

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

1 个答案:

答案 0 :(得分:1)

我认为你弄错了。 LocationManager是一个异步API,一旦有需要告诉你,它就会让你回调委托方法。

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

按照LocationManager实施的方式将您的代码与iOS对齐,然后在didUpdateLocations API中移动您的服务器调用。 请注意,此方法会根据位置更改被多次调用,因此,您可能需要仔细检查何时以及要将哪些数据发送到服务器。