【问题标题】:JSON parsing with SwiftyJSON - Trouble updating UI使用 SwiftyJSON 解析 JSON - 更新 UI 时遇到问题
【发布时间】:2019-06-11 00:48:41
【问题描述】:

我编写了以下从 Dark Sky API 中提取数据的代码。我正在用 SwiftyJSON 解析它,但我无法让我的 UI 标签“风”来显示风速。

我认为错误可能在我的解析中。我使用 JSON 编码器来查找我想要提取的参数,即 windSpeed,但我不知道是这部分我弄错了,还是在更新 UI 本身。当我对 API 执行 get 请求时,我还会收到多个请求实例,所以问题可能也源于那里?

我的代码如下:

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"
        }

    }
}

【问题讨论】:

  • 您可能确实想提供 JSON。你这样做:let windSpeed = json["currently"]["windSpeed"].doubleValue 是否至少:`json["currently"]` 返回了一些东西?然后json["currently"]["windSpeed"?会不会是 doubleValue 引起了问题?
  • 当我仅使用 [当前] 解析 json 时,我仍然在 UI 中一无所获。我试图将结果打印到调试控制台中,但我也没有得到任何东西......
  • 先下断点,看看windJSON有没有值。如果有,请确保在主线程上更新 UI。

标签: ios json swift swifty-json


【解决方案1】:

你有一些不合适的大括号。

func updateUIWithWindData() {

  wind.text = "\(windDataModel.speed)"

在此函数之后,将结束大括号紧跟在wind.text = "... 之后。结束大括号靠近类的底部。

另外,这个 else 语句还有一个不合适的大括号:

else {
  print("Error \(String(describing: response.result.error))") }
  self?.wind.text = "Connection issues"

print("Error... 行末尾的大括号应移到"Connection issues" 之后。

修复这些问题,您的代码应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多