Код: Выделить всё
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var apiData:[Countries] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.delegate = self
self.tableView.dataSource = self
fetchAPI()
}
func fetchAPI() {
let apiEndPoint = "https://restcountries.com/v2/all"
guard let url = URL(string: apiEndPoint) else {
print("Could not convert API endpoint to url object")
return
}
URLSession.shared.dataTask(with: url) { (data,response, error) in
if let err = error {
print("Error occured while fetching the data")
print(err)
return
}
if let jsonData = data {
do {
let decoder = JSONDecoder()
let decodedItem:[Countries] = try decoder.decode([Countries].self, from: jsonData)
DispatchQueue.main.async {
self.apiData = decodedItem
}
} catch let error {
print("An error occured during JSON decoding")
print(error)
}
}
}.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as UITableViewCell
return cell
}
}
Подробнее здесь: https://stackoverflow.com/questions/703 ... s-function
Мобильная версия