我的应用程序为用户提供了在应用程序中使用的天气源选择。我有Dark Sky,Open Weather和Accuweather都在工作。 (Accuweather需要一个单独的url会话来获取其位置密钥。仍在进行此操作。)
我想添加国家气象局,但我迷失了自己。那里太多了,太复杂了。我唯一需要的数据是一个纬度/经度。当前的温度,压力和%RH,以及下一小时左右降水的概率。 (开放天气不提供POP,Accuweather还需要另一个URL请求才能获得它。)
我怎样才能在Swift中制定URL会话以理想地获得一个返回我所需数据的会话?
这是我用于开始获取天气会话的代码。
func getWeather() { // Goes out to fetch the weather
var weatherStrings = getWeatherStrings() // Holds strings appropriate to each weather source
var urlString = weatherStrings[0] // The url to get the data
var weatherSite = weatherStrings[11] // Short name of the weather source
if let url = URL(string: urlString) { // Only proceeds with a valid URL
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("text/html", forHTTPHeaderField: "Content-Type")
let taskWeather = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
}
}
if let data = data, // Data has been received
// Do some processing of the weather data
var weatherReport = String(data: data, encoding: String.Encoding.utf8) {
var weatherResults = self.getWeatherResults(weatherStrings: weatherStrings, weatherReport: weatherReport)
var calcdWeatherResults = self.getCalcdWeatherResults(weatherResults: weatherResults)
var timeStamp = weatherResults[0] as! Date
let dateFormatter = DateFormatter() // format the date for output
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.timeStyle = DateFormatter.Style.short
var convertedDate = dateFormatter.string(from: timeStamp) // The timeStamp from the weather site
// Wrap up
let config = URLSessionConfiguration.default
let theSession = URLSession(configuration: config) // This is a dummy session for the next function
self.dispatchWeatherOutput(calcdWeatherResults: calcdWeatherResults, weatherResults: weatherResults, theSession: theSession)
} // Closes the IF data is not nil
} // Close Task
taskWeather.resume()
} // Closes the IF let URL
} // Close GetWeather function