Я новичок, пытающийся сделать приложение погоды похожим на стандартное приложение погоды на iphone.В настоящее время я работаю над экраном, на котором хранится список городов, составленный пользователем.Заранее благодарю за помощь!
Я заставил tableView работать, как только они выбирают ячейку, она закрывает tableViewController и загружает погода городов на предыдущем экране.Однако сейчас я пытаюсь добавить метку температуры в ячейку таблицы рядом с названием каждого города.
В верхней ячейке отображается текущее местоположение и используется для определения погоды их текущего местоположения.
Я знаю, что получаю погоду с помощью операторов Print, однако у меня возникают проблемы с перезагрузкой tableView, как только яЭто.Прямо сейчас идея, которую я пытаюсь сделать, это получить сохраненные названия городов, хранящиеся в coreData, и использовать эти названия городов для получения данных о погоде через JSON.Затем используйте json для отображения названия города и температуры города.
Я пытался поместить tableview.reload () во многие разные области.Я переместил вызов для функций, которые получают данные о погоде в разных точках.Ничто из того, что я пробовал, не работает.
let cityClassModel = [CityClass()]
var x = 0
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var savedCitiesArray = [SavedCityEntity]()
var savedDelegate : SavedCityChangeDelegate?
var isCelsius = true
var isCelsiusThree : Bool? {
didSet{
isCelsius = false
}
}
@IBOutlet weak var navBar: UINavigationBar!
//****************************************************************************
override func viewDidLoad() {
loadCities()
super.viewDidLoad()
tableView.rowHeight = 65.0
tableView.separatorStyle = .none
// cycle through array and get weather data for each stored city
if savedCitiesArray.count > 0 {
while x < savedCitiesArray.count {
let cityParams : [String : String] = ["q" : savedCitiesArray[x].cityName!, "appid" : APP_ID]
getTemperatures(url: CURRENT_WEATHER_URL, parameters: cityParams, cityNumber: x)
x +=1
}
//print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
}
tableView.reloadData()
}
//********************************************************************
// MARK: - Get City Temperature
func getTemperatures(url: String, parameters: [String : String], cityNumber: Int) {
Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
(response) in
if response.result.isSuccess {
print("Success got the weather data for cityList!")
let weatherJSON : JSON = JSON(response.result.value!)
self.updateTemperature(json: weatherJSON, cityNumber: cityNumber)
//print(weatherJSON)
} else {
//print("Error \(response.result.error)")
print("Connection Issues")
}
}
}
//MARK: - JSON Parsing
/**************************************************************************/
func updateTemperature(json : JSON, cityNumber: Int) {
//get current temperature
if let tempResult = json["main"]["temp"].double {
cityClassModel[cityNumber].cityClassName = json["name"].stringValue
//update data model temperature
cityClassModel[cityNumber].cityClassTemp = String(Int(tempResult - 273.15))
print("got temperature for cityList - \(cityClassModel[cityNumber].cityClassName) \(cityClassModel[cityNumber].cityClassTemp)")
} else {
// if for some reason unable to get weather data
print("Weather Unavailable")
}
self.tableView.reloadData()
}
// ****************************************************************************
// MARK: - Table view data source
//****************************************************************************
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return savedCitiesArray.count + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//declare cell
let cell = tableView.dequeueReusableCell(withIdentifier: "cityListCell", for: indexPath) as! CityCell
cell.delegate = self
// current location cell
if indexPath.row == 0 {
cell.textLabel?.text = "Current Location"
cell.accessoryType = .none
let cellBackgroundColour = HexColor(hexString: "2A5488")
if let color = cellBackgroundColour.darken(byPercentage: ((CGFloat(indexPath.row) / CGFloat(savedCitiesArray.count))) * 5) {
cell.backgroundColor = UIColor(complementaryFlatColorOf: color, withAlpha: 0.4)
cell.textLabel?.textColor = ContrastColorOf(backgroundColor: color, returnFlat: true)
}
}
// if cell is not the current location cell
else if indexPath.row <= savedCitiesArray.count {
var city = ""
var temp = ""
if cityClassModel[0].cityClassName != "" {
city = cityClassModel[indexPath.row - 1].cityClassName
temp = cityClassModel[indexPath.row - 1].cityClassTemp
}
cell.setCity(city: city, Temperature: temp)
cell.accessoryType = .none
let cellBackgroundColour = HexColor(hexString: "2A5488")
if let color = cellBackgroundColour.darken(byPercentage: ((CGFloat(indexPath.row) / CGFloat(savedCitiesArray.count)))) {
cell.backgroundColor = UIColor(complementaryFlatColorOf: color, withAlpha: 0.4)
cell.textLabel?.textColor = ContrastColorOf(backgroundColor: color, returnFlat: true)
}
}
return cell
}
//MARK: - city SELECTED in menu then becomes city in weatherView
//****************************************************************************
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// IF CURRENT LOCATION IS SELECTED
if indexPath.row == 0 {
//1 Get the city name the user entered in the text field
let cityName = "currentLocation"
//2 If we have a delegate set, call the method userEnteredANewCityName
savedDelegate?.userSelectedANewCity(city: cityName, units: isCelsius)
//3 dismiss the Change City View Controller to go back to the WeatherViewController
self.dismiss(animated: true, completion: nil)
print("Current Location Cell Clicked")
}
// IF A NEW CITY IS SELECTED
else if indexPath.row <= savedCitiesArray.count {
//1 Get the city name the user entered in the text field
let cityName = savedCitiesArray[indexPath.row - 1].cityName!
//2 If we have a delegate set, call the method userEnteredANewCityName
savedDelegate?.userSelectedANewCity(city: cityName, units: isCelsius)
//3 dismiss the Change City View Controller to go back to the WeatherViewController
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Save,Load, and Delete Functions
//****************************************************************************
//Save function (save city to list)
func saveCities() {
do {
try context.save()
} catch {
print("Error saving city/context \(error)")
}
self.tableView.reloadData()
}
//Load City from Data Model
func loadCities () {
let request : NSFetchRequest<SavedCityEntity> = SavedCityEntity.fetchRequest()
do {
savedCitiesArray = try context.fetch(request)
} catch {
print("Error fetching data from context \(error)")
}
}
//delete data from swipe
func updateModel(at indexPath: IndexPath) {
context.delete(savedCitiesArray[indexPath.row - 1])
savedCitiesArray.remove(at: indexPath.row - 1)
saveCities()
}
Клетки кажутся пустыми.(Изначально я мог получать только названия городов из coreData и заполнять их ячейками), но после попытки добавить названия городов с температурой я теперь ничего не получаю.
В идеале каждая ячейка будет отображать название города итекущая температура там