I have written the following code which pulls data from the Dark Sky API. I am parsing it with SwiftyJSON but then I can't get my UI label 'wind' to display the wind speed.
I think the error may be in my parsing. I have used a JSON encoder to find the parameter I want to pull i.e. windSpeed but I don't know if it is this part which I have got wrong or it is in updating the UI itself. When I do the get request for the API I also get multiple instances of the request so maybe the issue is stemming from there too?
My code is as follows:
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, CLLocationManagerDelegate {
let base_URL = "https://api.darksky.net/forecast/[API Key here]/"
//Instance variable
let locationManager = CLLocationManager()
let windDataModel = WindDataModel()
@IBOutlet weak var windDirectionArrow: UIImageView!
@IBOutlet weak var yard: UILabel!
@IBOutlet weak var gust: UILabel!
@IBOutlet weak var wind: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//Location manager set up
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
//Get wind data method
func getWindData(url: String, latitude: String, longitude: String) {
let urlStr = "\(base_URL)\(latitude),\(longitude)"
Alamofire.request(urlStr, method: .get, parameters:nil, encoding: JSONEncoding.default).responseJSON { [weak self] response in
if response.result.isSuccess {
print("Success! Got the weather data")
let windJSON : JSON = JSON(response.result.value!)
print(windJSON)
self!.updateWindData (json: windJSON)
} else {
print("Error \(String(describing: response.result.error))") }
self?.wind.text = "Connection issues"
}
}
//MARK: - JSON Parsing
/***************************************************************/
//
// //Write the updateWeatherData method here:
func updateWindData(json: JSON) {
let windSpeed = json["currently"]["windSpeed"].doubleValue
windDataModel.speed = Double(windSpeed)
updateUIWithWindData()
}
//// //Write the updateUIWithWeatherData method here:
func updateUIWithWindData() {
wind.text = "\(windDataModel.speed)"
//Did update method
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
self.locationManager.stopUpdatingLocation()
self.locationManager.delegate = nil
let latitude = String(location.coordinate.latitude)
let longitude = String(location.coordinate.longitude)
getWindData(url: base_URL, latitude: latitude, longitude: longitude)
}
}
//Did fail with error method
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
wind.text = "Error"
}
}
}