uitableview - Hi there , I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data -
i'm new ios development , i'm having hard time populating tableview embedded in uiviewcontroller json data.
''import uikit
class
firstviewcontroller:uiviewcontroller,uitableviewdatasource,uitableviewdelegate{
@iboutlet weak var tableview: uitableview! var tabledata:array< string > = array < string >() var valuetopass:string! override func viewdidload() { super.viewdidload() get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json") } override func didreceivememorywarning() { super.didreceivememorywarning() } func numberofsections(in tableview: uitableview) -> int { return 1 } func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int { return tabledata.count } func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecell(withidentifier: "firstviewcell", for: indexpath) cell.textlabel?.text = tabledata[indexpath.row] return cell } func get_data_from_url(_ 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 urlrequest, completionhandler: { ( data, response, error) in guard let _:data = data, let _:urlresponse = response , error == nil else { return } self.extract_json(data!) }) task.resume() } func extract_json(_ data: data) { let json: any? { json = try jsonserialization.jsonobject(with: data, options: []) } catch { return } guard let data_list = json as? nsarray else { return } if let countries_list = json as? nsarray { in 0 ..< data_list.count { if let country_obj = countries_list[i] as? nsdictionary { if let country_name = country_obj["country"] as? string { if let country_code = country_obj["code"] as? string { tabledata.append(country_name + " [" + country_code + "]") } } } } } dispatchqueue.main.async(execute: {self.do_table_refresh()}) } func do_table_refresh() { tableview.reloaddata() }
}
you need set tableview's datasource , delegate self.
Comments
Post a Comment