【问题标题】:UI won't update after getting json data from Openweathermap IOS 4 Xcode 10从 Openweathermap IOS 4 Xcode 10 获取 json 数据后 UI 不会更新
【发布时间】:2018-08-05 04:14:00
【问题描述】:

我的 JSON 已通过正确的值请求打印到控制台。但是 label.text 和 city.text 不会更新主控制器中的 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 提取到我的控制台

【问题讨论】:

  • 这行'self.updateMainUI()'代码被执行了吗?如果是,则尝试将其放在主线程中。 DisptachQueue.main.async { self.updateMainUI() }
  • 你打电话给startUpdatingLocation()了吗?
  • yes 已经解决了这个问题,但现在 Alamofire 不会无限停止请求 Json 数据。谢谢你的帮助

标签: ios json swift openweathermap xcode10


【解决方案1】:

这些行不会符合您的预期。

locationManager.requestWhenInUseAuthorization()
locationAuthStatus()

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

class ViewController: UITableViewController, CLLocationManagerDelegate {
// rest of 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()

}

【讨论】:

  • 非常感谢我实现了这个功能,它应该可以正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 2016-06-15
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
相关资源
最近更新 更多