UI 从 Openweathermap json 获取数据后不会更新 IOS 4 Xcode 10

UI won't update after getting json data from Openweathermap IOS 4 Xcode 10

我的 JSON 已打印出来以控制台正确的值请求。但是 label.text 和 city.text 不会在主控制器 UI 中更新 UI

@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var date: UILabel!
@IBOutlet weak var weatherType: UILabel!
@IBOutlet weak var degree: UILabel!
@IBOutlet weak var city: UILabel!

var currentWeather : CurrentWeather!

override func viewDidLoad() {
    super.viewDidLoad()
    currentWeather = CurrentWeather()

}
override func viewDidAppear(_ animated: Bool) {
    super .viewDidAppear(animated)
    locationAuthStatus()

}

    func locationAuthStatus() {
        if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            currentLocaion = locationManager.location
            //Location.sharedIntance.latitude = currentLocaion.coordinate.latitude
            //Location.sharedIntance.longitude = currentLocaion.coordinate.longitude
            print(currentLocaion)
            currentWeather.downloadWeatherDetail {
                downloadForecastData {
                    self.updateMainUI()
                }
            }

        } else {
            locationManager.requestWhenInUseAuthorization()
            locationAuthStatus()
        }
    }


func updateMainUI() {
    icon.image = UIImage(named: currentWeather.weatherType)
    city.text = currentWeather.cityName
    degree.text = "\(currentWeather.currentTemp)"
    weatherType.text = currentWeather.weatherType
    date.text = currentWeather.date
}

}

我是编码新手,我很难弄清楚为什么它没有显示,因为我确认我正在将数据从 Json 拉到我的控制台

这些行不会达到您的预期。

locationManager.requestWhenInUseAuthorization()
locationAuthStatus()

您对 requestWhenInUseAuthorization 的调用是异步的,应该由 CLLocationManagerDelegate 处理,它可以是您的视图控制器。你可以这样做:

class ViewController: UITableViewController, CLLocationManagerDelegate {
// rest of class

将这些功能添加到您的 class

func locationManager(_ manager: CLLocationManager, didUpdateLocations objects: [CLLocation]) {
    let location = objects[objects.count-1]
    let currentLocation = location
        print(currentLocation)
        currentWeather.downloadWeatherDetail {
            downloadForecastData {
                self.updateMainUI()
            }
        }
}

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

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    locationManager.startUpdatingLocation()

}