首页 > 解决方案 > 获取日出和日落时间

问题描述

我正在尝试获取日出和日落,我正在使用开放天气 API 来获取纬度和经度。有没有办法使用纬度和经度来获取任何城市的日出和日落时间?

extension WeatherViewController: CLLocationManagerDelegate {

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        let lat = location.coordinate.latitude
        let lon = location.coordinate.longitude
        weatherManager.fetchWeather(latitude: lat, longitude: lon)
    }
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

}

我的天气经理

   var delegate: weatherManagerDelegate?

func fetchWeather(cityName: String){
    let urlString = "\(weatherURL)&q=\(cityName)"
    performRequest(with: urlString)
}

func fetchWeather(latitude: CLLocationDegrees, longitude: CLLocationDegrees){
    let urlString = "\(weatherURL)&lat=\(latitude)&lon=\(longitude)"
    performRequest(with: urlString)
}

标签: iosswiftiphone

解决方案


找出答案:

对于 json,我使用了 SwiftyJson 库.......

            let sunriseTime = myResult["sys"]["sunrise"].doubleValue
            
            let sunriseDate = Date(timeIntervalSince1970:  sunriseTime)
             let formatter = DateFormatter()
             formatter.dateStyle = .none
             formatter.timeStyle = .medium

             let formattedTime = formatter.string(from: sunriseDate)
             DispatchQueue.main.async {
                 self.lblwindspeed.text = "Sunrise: \(formattedTime)"
             }

//输出:日出:上午 5:11:03 在此处输入图像描述


推荐阅读