如何仅从JSON中获取特定值?斯威夫特4

时间:2018-07-03 10:11:08

标签: ios json swift

我当时正在制作一个可以在“白天”和“晚上”显示温度的天气应用程序。 为此,我需要从下面给出的API中获取数据。

here

如果您已经检查过,问题是我只需要从“ 3:00 AM”和“ 15:00” /“ 3:00 PM”时间获取温度,而忽略其他时间和温度。然后,我必须将其显示在我的UICollectionView上(由我自己完成)

我知道可以使用DateFormatter并从“ dt”或“ dt_txt”中获取一个值来完成此操作。但是,我确实需要知道如何实现。源将被附加。任何帮助将不胜感激。除了我的问题以外,您注意到的任何错误也将不胜感激。 :]

ViewController:注意:请仅查看UICollectionView函数,我添加了其他函数仅供参考

class SecondTaskVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var weatherModel: WeatherModelDecodable?
    let weatherMmodel = [WeatherModelDecodable]()
    var listModel = [ListDecodable]()

    let textArray = ["понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресенье"]


    @IBOutlet weak var tempLabel: UILabel!

    @IBOutlet weak var cityLabel: UILabel!

    @IBOutlet weak var descrpLabel: UILabel!

    @IBOutlet weak var dateLabel: UILabel!

    override func viewDidLoad() {

        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())


    }

    // UICollectionView

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return textArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WeatherCollectionViewCell", for: indexPath) as! WeatherCollectionViewCell

        let urlString = "https://api.openweathermap.org/data/2.5/forecast?lat=42.874722&lon=74.612222&APPID=079587841f01c6b277a82c1c7788a6c3"
        let url = URL(string: urlString)
        Alamofire.request(url!).responseJSON { (response) in
            let result = response.data
            do{
                let decoder = JSONDecoder()
                self.weatherModel = try decoder.decode(WeatherModelDecodable.self, from: result!)
                if let tempToConvert = self.weatherModel?.list[indexPath.row].main.temp{

                    // CHECK THIS, I KNOW IT IS NOT CORRECT, BUT YOU GET ME.
                    if let timeResult = (self.weatherModel?.list[indexPath.row].dt) {
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateStyle = .none
                        dateFormatter.timeStyle = .short

                        let date = Date(timeIntervalSince1970: Double(timeResult))
                        if dateFormatter.string(from: date) == "3:00 AM"{
                            cell.dayTemp.text = String(format: "%.0f", tempToConvert - 273.15) + "°C"
                            self.tempLabel.text = String(format: "%.0f", tempToConvert - 273.15) + "°C"
                    }
                        if dateFormatter.string(from: date) == "3:00 PM"{
                            cell.dayTemp.text = "4 c"
                            //self.tempLabel.text = String(format: "%.0f", tempToConvert - 273.15) + "°C"
                        }
                    }
                    ///////
                }
                self.cityLabel.text = self.weatherModel?.city.name
                self.dateLabel.text = self.weatherModel?.list[indexPath.row].dtTxt

                // displaying date and the week
            if  let dateResult = (self.weatherModel?.list[indexPath.row].dt) {
                let date = Date(timeIntervalSince1970: TimeInterval(dateResult))
                let dateFormatter = DateFormatter()
                dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
                dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
                let localDate = dateFormatter.string(from: date)
                let str = localDate.components(separatedBy: " 2018")
                let dd = localDate.replacingOccurrences(of: str[0], with: self.textArray[indexPath.row])
                let stringg = dd.components(separatedBy: " ")
                cell.dayCollection.text = stringg[0]
                print(stringg[0])
            }
        }catch let error{
            print("error in decoding",error.localizedDescription)
        }
    }
    return cell
}
 }

数据模型:如果重要的话

struct WeatherModelDecodable: Codable {
    let list: [ListDecodable]
    let city: CityDecodable
    enum CodinKeys: String, CodingKey{
        case list = "list"
        case city = "city"
    }
}

struct CityDecodable: Codable {
    let name: String
}
struct ListDecodable: Codable {
    let dt: Int
    let main: MainClassDecodable
    let weather: [WeatherDecodable]
    let wind: WindDecodable
    let dtTxt: String

enum CodingKeys: String, CodingKey{
    case dt = "dt"
    case main = "main"
    case weather = "weather"
    case wind = "wind"
    case dtTxt = "dt_txt"
}

 }
struct MainClassDecodable: Codable {
     let temp: Double
     let tempMin: Double
     let tempMax: Double
     let pressure: Double
     let humidity: Int

enum CodingKeys: String, CodingKey {
    case temp = "temp"
    case tempMin = "temp_min"
    case tempMax = "temp_max"
    case pressure = "pressure"
    case humidity = "humidity"
    }
}
struct WeatherDecodable: Codable {
     let main: String
     let description: String

enum CodingKeys: String, CodingKey {
    case main = "main"
    case description = "description"
}
}
struct WindDecodable: Codable {
     let speed: Double
     let deg: Double
}

如果您需要任何可以帮助我解决此问题的方法,请随时提出。

1 个答案:

答案 0 :(得分:2)

  • 首先,如果您将&units=metric插入URL查询中,则会在°C中获得度数(无需转换)。
  • 第二,如果您使用日期解码策略 .secondsSince1970,则可以将dt解码为Date(无需转换)。
  • 如果您使用密钥解码策略 .convertFromSnakeCase,则可以省略所有的CodingKeys。

这是结构的简化版本,省略了名称中Decodable的重复出现,dt将被解码为Date

struct WeatherModel : Decodable {
    let cod : String
    let list : [List]
}

struct List : Decodable {
    let weather : [Weather]
    let main : Main
    let dt : Date
}

struct Weather : Decodable {
    let main : String
    let description : String
}

struct Main: Decodable {
    let temp : Double
    let tempMin : Double
    let tempMax : Double
    let pressure : Double
    let humidity : Int
}

使用提及的策略

解码JSON
do {
     let decoder = JSONDecoder()
     decoder.keyDecodingStrategy = .convertFromSnakeCase
     decoder.dateDecodingStrategy = .secondsSince1970
     self.weatherModel = try decoder.decode(WeatherModel.self, from: result!)

要过滤3AM / 3PM日期,您首先需要将本地时间与UTC进行区分

     let utcDifference = TimeZone.current.secondsFromGMT() / 3600

现在过滤list数组

     let threeAMPMForecast = self.weatherModel.list.filter{
         let hour = Calendar.current.component(.hour, from: $0.dt)
         return hour == (3 + utcDifference) || hour == (15 + utcDifference)
     }
     print(threeAMPMForecast)
     // or to print all temperatures
     print(threeAMPMForecast.map{ $0.main.temp }) 

} catch {
    print(error)
}

请在游乐场中尝试代码。