swift - locationManager 函数在代码末尾触发

标签 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)")
        }

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

控制台输出如下:

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

最佳答案

我想你搞错了。 LocationManager 是一个异步 API,一旦委托(delegate)方法有需要告诉您的信息,它就会给您回调。

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

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

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

相关文章:

ios - Firebase -'isDirectChannelEstablished' 已弃用 : FCM direct channel is deprecated, 请使用 APNs channel 进行下游消息传递

ios - 链接无法从 iOS 9.0 中的 safari 应用程序打开,但在 iOS 9.3 中有效

ios - StoreKit 的 finishTransaction 崩溃

swift - 我在使用 Swift 2.0 接收用户当前位置时遇到困难

ios - 在两个 iOS 设备之间发送数据,其中一个充当 iBeacon

html - 如何在 iOS 中删除字符串中的评论 HTML 元素

ios - Swift 5 反射获取类属性列表并调用它们

iphone - 电话链接在 iOS 9 中不起作用

ios - 触摸 map 时 MKUserLocation 停止更新

swift - 是否有任何解决方法可以将存储的属性快速放入扩展中?