我正在尝试使用CLLocation捕获经度和纬度,然后使用Alamofire中的经度和纬度来获取天气。每次,经度和纬度都不会停止更新,天气数据也不会打印出来(如果你想在这里查看数据的示例链接:http://forecast.weather.gov/MapClick.php?lat=37.33233141&lon=-122.0312186&FcstType=json)
class SampleViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
var startLocation: CLLocation!
var isFetchingWeather = false
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
override func viewDidAppear(_ animated: Bool) {
getCurrentLocation()
}
func getCurrentLocation(){
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var userLocation:CLLocation = locations[0]
if isFetchingWeather != false{
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
let requestLink = "http://forecast.weather.gov/MapClick.php?lat=\(userLocation.coordinate.latitude)&lon=\(userLocation.coordinate.longitude)&FcstType=json"
print(requestLink)
Alamofire.request(requestLink).validate().responseJSON
{ response in
switch response.result {
case .success(let data):
let json = JSON(data)
self.weatherData = json["data"].arrayValue
for weather in self.weatherData{
let temp = weather["weather"].stringValue
self.weatherString.append(temp)
}
print (self.weatherString)
if self.startLocation == nil {
self.startLocation = userLocation as! CLLocation
self.locationManager.stopUpdatingLocation()
}
case .failure(let error):
print(error)
}
}
}
else{
print("is fetching weather is false")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}
感谢。
答案 0 :(得分:0)
设置一个标志以指示何时开始获取天气信息,如果设置了该标志,则不要调用Alamofire来获取天气信息。例如,您可以在声明startLocation
:
var isFetchingWeather = false
然后,在locationManagerdidUpdateLocations
中首先检查isFetchingWeather
是否为假。如果没有,请返回。否则,请获取天气信息。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if isFetchingWeather {
return
}
isFetchingWeather = true
// Do the actual weather fetching
}
当然,您可能希望在获得一些位置更新后实际获取天气,因为最初的位置更新可能不准确:)
答案 1 :(得分:0)
您真的不应该在您的位置代表中运行您的天气请求。而是在admin-on-rest
委托中获取您的位置并将其保存到var。接下来,拨打didUpdateLocations
,然后拨打单独的功能以发出天气请求。像这样:
stopUpdatingLocation()