Step - 1 : Create Model Country Class using .swift file. Like,
Step - 2 : In ViewController put this function. Like,
import UIKit
struct Country:Decodable {
var name = String()
var capital = String()
//var type:CellType = .Country
//var languages = [Languages]
}
struct Languages:Decodable
{
var iso639_1 = String()
var name = String()
var nativeName = String()
}
Step - 2 : In ViewController put this function. Like,
func getDataApi(){
//2
var urlRequest:URLRequest = URLRequest.init(url: url)
urlRequest.httpMethod = "GET"
//3
let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if error != nil
{
print(error?.localizedDescription as Any)
}
else if (data != nil)
{
if let data = data
{
do{
var countries = try JSONDecoder().decode(Array<Country>.self, from: data)
print(countries)
self.record = countries
DispatchQueue.main.async
{
self.tblCountry.dataSource = self
self.tblCountry.reloadData()
}
}
catch{
print(error.localizedDescription)
}
}
}
}
dataTask.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(record.count)
return record.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:CountryCell = tableView.dequeueReusableCell(withIdentifier: "CountryCell") as! CountryCell
cell.lblName.text = record[indexPath.row].name
return cell
}
No comments:
Post a Comment