0
我試圖讓我的代碼獲取用戶的當前位置並將其發送到服務器。當我運行我的代碼時,似乎LocationManager
函數僅在我的startload
函數中的所有內容完成後纔會觸發。我試圖在之前將用戶的位置發送到服務器。在代碼結束時觸發的locationManager函數
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
您能澄清一下您的意思嗎?「在didUpdateLocations中移動服務器調用?」 –
我的意思是 - 你應該等到'LocationManager'調用委託方法'didUpdateLocations'。一旦你有可用的數據,然後只有服務器調用來發布服務器上的數據。 – Abhinav