gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:10:18 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com