2017-01-24 2 views
1

웹 사이트에서 데이터를 구문 분석하고 단추 누르기로 tableview에 표시하려고합니다. 나는 스위프트 3, Xcode 8.2 베타를 사용하고 있으며, 배열에 저장하거나 tableView에 표시 할 데이터를 얻을 수 없습니다.데이터를 Tableview Swift로 구문 분석 3

코드에서 많은, 많은 문제가 있습니다
import UIKit 
class SecondViewController: UIViewController, UITableViewDelegate,UITableViewDataSource { 
let urlString = "https://jsonplaceholder.typicode.com/albums" 
@IBOutlet weak var tableView: UITableView! 
    var titleArray = [String]() 
    var userIdArray = [String]() 
@IBAction func getDataButton(_ sender: Any) { 
    self.downloadJSONTask() 
    self.tableView.reloadData() 
} 
override func viewDidLoad() { 
    super.viewDidLoad() 
    tableView.dataSource = self 
    tableView.delegate = self 
} 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 

func downloadJSONTask() { 
    let url = NSURL(string: urlString) 
    var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) 
    downloadTask.httpMethod = "GET" 


    URLSession.shared.dataTask(with: (url! as URL), completionHandler: {(Data, URLResponse, Error) -> Void in 
     let jsonData = try? JSONSerialization.jsonObject(with: Data!, options: .allowFragments) 
      print(jsonData as Any) 
     if let albumArray = (jsonData! as AnyObject).value(forKey: "") as? NSArray { 
      for title in albumArray{ 
       if let titleDict = title as? NSDictionary { 
        if let title = titleDict.value(forKey: "title") { 
         self.titleArray.append(title as! String) 
         print("title") 
         print(title) 
        } 
        if let title = titleDict.value(forKey: "userId") { 
         self.userIdArray.append(title as! String) 
        } 
        OperationQueue.main.addOperation ({ 
         self.tableView.reloadData() 
        }) 
       } 
      }     
     }   
    }).resume()  
    } 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    return titleArray.count 
    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell 
    cell.titleLabel.text = titleArray[indexPath.row] 
    cell.userIdLabel.text = userIdArray[indexPath.row] 
    return cell 
    } 
    } 

답변

0

, 최악의 스위프트에 NSArray/NSDictionary을 사용하는 것입니다

class TableViewCell: UITableViewCell { 
@IBOutlet weak var userIdLabel: UILabel! 
@IBOutlet weak var titleLabel: UILabel! 
override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
} 

가 여기 내의 ViewController 코드 : 여기 내 tableViewCell 클래스입니다.

json으로는 사전의 배열, 키 title의 값은 userID의 값이 Int입니다 String, 그래서 당신은

var titleArray = [String]() 
var userIdArray = [Int]() 

가 서로의 대부분 지정되지 않은 Any에 JSON 데이터를 캐스팅하지 마십시오 당신의 배열을 선언해야 안돼. 항상 실제 유형으로 전송하십시오. 또 하나의 큰 문제는 클로저에있는 Data 매개 변수가 기본 구조체와 Swift3에 충돌하는 것입니다. 항상 소문자 매개 변수 레이블을 사용하십시오. 요청은 코드에서 전혀 사용되지 않습니다. 그리고 Swift 3에서는 항상 기본 구조체 URL, Data, URLRequest 등을 사용합니다. 마지막으로 은 JSON이 컬렉션 유형으로 명확하게 시작하기 때문에 난센스입니다.

let url = URL(string: urlString)! 
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20) 
URLSession.shared.dataTask(with: request) { (data, response, error) in 
    if error != nil { 
     print(error!) 
     return 
    } 

    do { 
     if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:Any]] { 
      print(jsonData) 
      for item in jsonData { 

       if let title = item["title"] as? String { 
        titleArray.append(title) 
       } 
       if let userID = item["userId"] as? Int { 
        userIdArray.append(userID) 
       } 
       DispatchQueue.main.async { 
        self.tableView.reloadData() 
       } 
      } 
     } 
    } catch let error as NSError { 
     print(error) 
    } 
}.resume() 

추 신 : 두 개의 별도 어레이를 데이터 소스로 사용하는 것은 너무 끔찍합니다. 선택적 바인딩 중 하나가 실패하고 배열의 항목 수가 다를 것이라고 가정 해보십시오. 그것은 런타임 크래시에 대한 초대장입니다.

+0

도움 주셔서 감사합니다. 내가 볼 수 있듯이 셀에 데이터를 올바르게로드하는 방법을 알기 위해 길을 잃었습니다. 도와 주셔서 정말 감사합니다. 셀에 데이터를로드 할 때이 줄에서 오류가 발생합니다. "cell.userIdLabel.text = userIdArray [indexpath.row]"에서 "Int 값을 String 유형에 할당 할 수 없습니다"중 하나입니다. 셀 텍스트 레이블에 Int를로드하는 방법이 있습니까? – JeffBee

+0

더 이상'Int' 타입이 필요 없다면'userIdArray'를'[String]'으로 선언하고'userIdArray.append ("\ (userID)"배열을 채 웁니다. ") – vadian

+0

다시 한번 감사드립니다! 이 프로젝트는 학습 경험이며 귀하의 도움은 매우 중요합니다. 나는 응용 프로그램 개발에 익숙하지 않고 귀하의 권고를 따를 것입니다. – JeffBee

관련 문제