본문 바로가기
ios 뽀개기/ios 응용해보기

json parser

by 인생여희 2017. 12. 18.
반응형

json parser


//찾아볼것

//1. 구조체

//2. json 파서

//3. de catch

//4 JSONDecoder

//5. DispatchQueue


import UIKit

//구조체 만들기


struct Weather:Decodable {

    let country: String

    let weather: String

    let temperature:String

}


class ViewController: UIViewController,UITableViewDataSource{


    

    var datalist = [Weather]()

    

    @IBOutlet weak var mainTableView: UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        

        let jsonUrlString = "https://raw.githubusercontent.com/ChoiJinYoung/iphonewithswift2/master/swift4weather.json"

        

        guard let jsonURL = URL(string:jsonUrlString) else {

            return

        }

        

        //

        URLSession.shared.dataTask(with: jsonURL, completionHandler: {(

            data,response,error) -> Void in

            guard let data = data else{return}

            

            do{

                //백그라운드 스레드에서 작동하는 코드

                    self.datalist = try JSONDecoder().decode([Weather].self, from: data)

                    print(self.datalist)

                

                    //백그라운드에서 메인(뷰)으로 접근할 수 없다.

                    //self.mainTableView.reloadData()

                DispatchQueue.main.async(execute: {

                    self.mainTableView.reloadData()

                })

            }catch{

                print("parsing error\(error)")

            }

            

        }).resume()

        

    }

   


   


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return datalist.count

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WeatherViewCell

    

        let structTemp = datalist[indexPath.row]

        

        cell.contryLable.text = structTemp.country

        let weatherStr = structTemp.weather

        

        

        cell.weatherLable.text = weatherStr

        cell.temLable.text = structTemp.temperature

        

        if weatherStr == "맑음" {

            cell.imgView.image = UIImage(named:"sunny.png")

        }else if weatherStr == "비" {

            cell.imgView.image = UIImage(named:"rainy.png")

        }else if weatherStr == "흐림" {

            cell.imgView.image = UIImage(named:"cloudy.png")

        }else if weatherStr == "눈" {

            cell.imgView.image = UIImage(named:"snow.png")

        }else {

            cell.imgView.image = UIImage(named:"blizzard.png")

        }

        

        return cell

    }

}







//

//  WeatherViewCell.swift

//  XML

//

//  Created by MacBookPro on 2017. 12. 18..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit


class WeatherViewCell: UITableViewCell {

    @IBOutlet weak var contryLable: UILabel!

    @IBOutlet weak var weatherLable: UILabel!

    @IBOutlet weak var temLable: UILabel!

    @IBOutlet weak var imgView: UIImageView!

    

    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }


    override func setSelected(_ selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)


        // Configure the view for the selected state

    }


}







[
    {
    "country": "한국",
    "weather": "비",
    "temperature": "20"
    },
    {
    "country": "일본",
    "weather": "맑음",
    "temperature": "19"
    },
    {
    "country": "중국",
    "weather": "눈",
    "temperature": "14"
    },
    {
    "country": "스페인",
    "weather": "우박",
    "temperature": "13"
    },
    {
    "country": "미국",
    "weather": "흐림",
    "temperature": "2"
    },
    {
    "country": "영국",
    "weather": "비",
    "temperature": "10"
    },
    {
    "country": "프랑스",
    "weather": "흐림",
    "temperature": "15"
    },
    {
    "country": "브라질",
    "weather": "흐림",
    "temperature": "35"
    },
    {
    "country": "스위스",
    "weather": "맑음",
    "temperature": "13"
    },
    {
    "country": "덴마크",
    "weather": "비",
    "temperature": "2"
    },
    {
    "country": "스웨덴",
    "weather": "눈",
    "temperature": "0"
    },
    {
    "country": "네덜란드",
    "weather": "비",
    "temperature": "12"
    },
    {
    "country": "크로아티아",
    "weather": "맑음",
    "temperature": "30"
    },
    {
    "country": "필리핀",
    "weather": "맑음",
    "temperature": "28"
    },
    {
    "country": "독일",
    "weather": "눈",
    "temperature": "3"
    },
    {
    "country": "헝가리",
    "weather": "비",
    "temperature": "13"
    },
    {
    "country": "벨기에",
    "weather": "흐림",
    "temperature": "8"
    },
    {
    "country": "핀란드",
    "weather": "우박",
    "temperature": "15"
    },
    {
    "country": "이탈리아",
    "weather": "맑음",
    "temperature": "23"
    }
]


반응형

'ios 뽀개기 > ios 응용해보기' 카테고리의 다른 글

mac에서 php를 통해서 mysql에 삽입하기  (0) 2017.12.19
php에서 myql파일 json으로 가져오기  (0) 2017.12.19
xml parser  (0) 2017.12.18
페이지 뷰  (0) 2017.12.15
탭뷰  (0) 2017.12.15

댓글