2017-10-25 1 views
0

json.personal을 구문 분석 할 때 새로운 기능입니다. 단일 뷰 응용 프로그램을 만들었습니다.이 함수를 사용하여 URL에서 json을 얻었습니다.Swift를 사용하여 tableview에서 Json을 구문 분석

func parseData(){ 
     //created URL 
     guard let requestURL = URL(string: "https://machla.bh/api-category2") else {return } 

     //creating URLRequest 
     var request = URLRequest(url: requestURL) 

     //setting the method to post 
     request.httpMethod = "POST" 

     //creating the post parameter by concatenating the keys and values from text field 
     var postParameters = "" 

     postParameters += "key=LpfyirxoNOfP8wPns4nZqTw6DQ4wY A2q6yvpKsof6gkYDTykVXSEonTO2VB HE2zRdqrvsyoyMVyRagWtKAtVuOuNs c7QW5KrgbXS8SqPZ7sIDlPEvhBWyo5 NoObAcor3GlO87nRSaFdxhKDRTiBkK 3pFsTQyffzuBdIBiM8zFra6Yh8NbbC QQaratgFFE2hzLouNEIHq88xaSqum1 C0z7g325i3hixT5oLSo5tvhpvvdTJO WohfqGSakeGz7hsAU" 

     postParameters += "&path=59" 

     postParameters += "&language_id=1" 

     //adding the parameters to request body 
     request.httpBody = postParameters.data(using: .utf8) 

     //creating a task to send the post request 
     let session = URLSession.shared 

     let task = session.dataTask(with: request) { data, response, error in 

      guard error == nil else { 
       print("error is \(error!.localizedDescription)") 
       return 
      } 
      guard let data = data else { 
       print("No data was returned by the request!") 
       return 
      } 


      // print data from request 
      let str = String(data: data, encoding: .utf8)! 
       print(str) 
      for eachFetechedCountry in str 
      { 
       let eachCountry=eachFetechedCountry as! [String:Any] 
       let category = eachCountry["categories"] as! String 
       let product=eachCountry["products"] as! String 
       self.fetchcountry.append(Country(categories: category, products: product)) 

      } 
      self.countryTableView.reloadData() 

     } 

     //executing the task 
     task.resume() 

    } 

나는 JSON에서 범주 및 제품을 읽을 양반 아하지 않는 이상 function.These 문에서 다음 문을 사용하여 JSON에서 범주 및 제품을 읽기 위해 노력하고 있어요?

for eachFetechedCountry in str 
       { 
        let eachCountry=eachFetechedCountry as! [String:Any] 
        let category = eachCountry["categories"] as! String 
        let product=eachCountry["products"] as! String 
        self.fetchcountry.append(Country(categories: category, products: product)) 

       } 

테이블보기로 범주와 제품을 채우기 위해 내가 범주를 채우는 방법을

func tableView(_ tableViewr: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = countryTableView.dequeueReusableCell(withIdentifier: "cell") 
     cell?.textLabel?.text=fetchcountry[indexPath.row].category 
     cell?.detailTextLabel?.text=fetchcountry[indexPath.row].product 
     return cell! 

    } 

코딩 테이블보기로 범주와 제품을 채우기위한 클래스라는 이름의 국가

class Country{ 

    var product:String 
    var category:String 

    init(categories :String, products:String) 
    { 
     self.category=categories 
     self.product=products 
    } 

} 

을 생성 테이블보기로 제품?

이 링크에서 수정을 위해 샘플 프로젝트를 다운로드 할 수 있습니까? https://drive.google.com/file/d/0B5pNDpbvZ8SnY3RicXpGN1FYbXc/view?usp=sharing

+0

https://www.raywenderlich.com/150322/swift-json-tutorial-2 –

+0

https://developer.apple.com/swift/blog/ ? id = 37 –

+0

JSON 구문 분석에 관한 질문은 여기에있는 5 가지 질문 중 하나입니다. 검색 했습니까? [2700 개 이상의 관련 질문이 있습니다] (https://stackoverflow.com/search?q=%5Bswift%5D+parse+json). JSON 데이터를 deserialize하는 단계를 놓쳤다. – vadian

답변

0

스위프트 4 - 디코딩 가능 프로토콜의 기능을 사용해야합니다.

let task = session.dataTask(with: request) { data, response, error in 

     guard error == nil else { 
      print("error is \(error!.localizedDescription)") 
      return 
     } 

     guard let data = data else { 
      print("No data was returned by the request!") 
      return 
     } 

     do { 
      let country = try JSONDecoder().decode(Country.self, from: data) 

      // do what you want here with Country array 
      // ... 

     } catch let error { 
      // catch error and handled it here 
     } 

     DispatchQueue.main.async { 
      self.countryTableView.reloadData() 
     } 
    } 

    //executing the task 
    task.resume() 

항상 메인 스레드에서 tableview를 업데이트하십시오 !!!

그리고 사용하는 구조체 :

struct Country: Decodable{ 
    var categories: [Category] 
} 

struct Category: Decodable { 
    var name: String 
    var products: [Product] 
} 

struct Product: Decodable { 
    var name: String 
} 
+0

json에서 카테고리 및 제품을 얻는 방법. let str = String (data : data, encoding : .utf8)! print (str) –

+0

카테고리를 가져올 수 있습니다. categories = country.categories 예 : let firstProduct = country.categories.first? .products.first –

+0

json에서 데이터를 가져 와서 데이터를 테이블보기로 채우려합니다. do {let country = try JSONDecoder(). decode (myCountry.self, from : data) let categories = country.categories.first? .name let firstProduct = country.categories.first? .products.first? .name self.fetchcountry. append (Country (categories : categories!, products : firstProduct!))} catch let error {} ----------- 카테고리 이름과 제품 이름이 없습니까? 컴파일러는 더 이상 읽을 수 없습니다 (try country try = try JSONDecoder(). decode (myCountry.self, from : data)) tryafter 시도가 실패하면 try가 catch됩니다. –

관련 문제