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
}
}
도움 주셔서 감사합니다. 내가 볼 수 있듯이 셀에 데이터를 올바르게로드하는 방법을 알기 위해 길을 잃었습니다. 도와 주셔서 정말 감사합니다. 셀에 데이터를로드 할 때이 줄에서 오류가 발생합니다. "cell.userIdLabel.text = userIdArray [indexpath.row]"에서 "Int 값을 String 유형에 할당 할 수 없습니다"중 하나입니다. 셀 텍스트 레이블에 Int를로드하는 방법이 있습니까? – JeffBee
더 이상'Int' 타입이 필요 없다면'userIdArray'를'[String]'으로 선언하고'userIdArray.append ("\ (userID)"배열을 채 웁니다. ") – vadian
다시 한번 감사드립니다! 이 프로젝트는 학습 경험이며 귀하의 도움은 매우 중요합니다. 나는 응용 프로그램 개발에 익숙하지 않고 귀하의 권고를 따를 것입니다. – JeffBee