여기서도 TableViewController에서 다른 ViewController로 올바른 데이터를 전달하는 방법을 아직 알아 내지 못한 똑같은 문제가 발생 합니다. JSON에서 데이터를 가져옵니다. 필요한 모든 것이 있지만 표시되는 행 데이터를 선택하면 마지막 행의 데이터가 표시됩니다. TableViewController를 선택한 정확한 행에 대한 정보를 가져와야합니다.
import UIKit
class TableViewController: UITableViewController {
var TableData:Array< String > = Array < String >()
func getData(_ link: String) {
let url: URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _: Data = data , let _: URLResponse = response , error == nil else {
return
}
self.extractJSON(data!)
})
task.resume()
}
func extractJSON(_ data: Data) {
let json: Any?
do {
json = try JSONSerialization.jsonObject(with: data, options: [])
} catch {
return
}
guard let dataList = json as? NSArray else {
return
}
if let countriesList = json as? NSArray {
for i in 0 ..< dataList.count {
if let countriesObj = countriesList[i] as? NSDictionary {
if let countryName = countriesObj["country"] as? String {
if let countryCode = countriesObj["code"] as? String {
TableData.append(countryName + " [" + countryCode + "]")
UserDefaults.standard.set(String(describing: countryName), forKey: "name")
UserDefaults.standard.set(String(describing: countryCode), forKey: "code")
UserDefaults.standard.synchronize()
}
}
}
}
}
DispatchQueue.main.async(execute: {self.doTableRefresh()})
}
func doTableRefresh() {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
getData("http://www.kaleidosblog.com/tutorial/tutorial.json")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return TableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
}
tableViewDidSelectRowAtIndexPath
Delegate Method를 사용할 수 있습니다.
let string = TableData[indexPath.row]
데이터를 가져 와서 vc에 전달하려면
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let string = TableData[indexPath.row]
let vc = // Your VC From Storyboard
vc.data = string //
self.navigationController?.pushViewController(vc, animated: true)
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다