My tableView does not show the data. I am fetching the data through api and save it into separate class with initializers. But it does not the show on the tableView. How to resolve this issue. I am new to iOS. I know there is only one line of code problem somewhere.
I call api in viewDidLoad method.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
//fetch all expected visitor data
self.apiExpectedVisitor(strURL: urlViewExpectedVisitors)
self.expectedTableView.reloadData()
}
Function of API Method
func apiExpectedVisitor(strURL: String)
{
fetchedExpectedData = []
//URL
let myURL = URL(string: strURL)
//URL Request
let request = NSMutableURLRequest(url: myURL!)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
let token = "Bearer " + strToken
request.addValue(token, forHTTPHeaderField: "Authorization")
let postTask = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
print(response!)
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: [Any]] {
print("POST Method :\(json)")
DispatchQueue.main.async {
for expectedVisitors in json["expected_visitors"]!
{
let eachData = expectedVisitors as! [String: Any]
let id = eachData["id"] as! Int
let name = "\(String(describing: eachData["name"]))"
let email = "\(String(describing: eachData["email"]))"
let phone = eachData["phone"] as! String
let verification_code = "\(String(describing: eachData["expected_visitor_verification_code"]))"
let qr_code = eachData["expected_visitor_qr_code"] as? String
let isVisited = eachData["is_visited"] as! Int
let company_id = eachData["company_id"] as! Int
let purpose = "\(String(describing: eachData["purpose"]))"
let meeting_date = eachData["meeting_date"] as! String
let meeting_time = eachData["meeting_time"] as! String
let created_at = eachData["created_at"] as! String
let updated_at = eachData["updated_at"] as! String
//Date.formatter(createdDate: createdDate)
if let department_id = eachData["department_id"] as? Int, let employee_id = eachData["employee_id"] as? Int, let location_id = eachData["location_id"] as? Int, let image = eachData["image"] as? String, let duration = eachData["duration"] as? String {
fetchedExpectedData.append(FetchedAllExpectedVisitors.init(id: id, name: name, email: email, phone: phone, department_id: department_id, employee_id: employee_id, location_id: location_id, image: image, verification_code: verification_code, qr_code: qr_code!, isVisited: isVisited, company_id: company_id, purpose: purpose, meeting_date: meeting_date, meeting_time: meeting_time, duration: duration, created_at: created_at, updated_at: updated_at))
self.expectedTableView.reloadData()
}
}
}
}
} catch let error {
print(error.localizedDescription)
}
}
postTask.resume()
}
TableView DataSource and Delegate Methods
func numberOfSections(in tableView: UITableView) -> Int {
return fetchedExpectedData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ShowExpectedCell", for: indexPath) as! ShowExpectedTVCell
cell.lblDate.text = fetchedExpectedData[indexPath.section].created_at
cell.lblVisName.text = fetchedExpectedData[indexPath.section].name
print(fetchedExpectedData[indexPath.section].name)
for i in 0..<fetchedDepttData.count {
let department_id = fetchedDepttData[i].depttID
if fetchedExpectedData[indexPath.section].department_id == department_id
{
cell.lblDeptt.text = fetchedDepttData[i].depttName
}
}
for i in 0..<fetchedEmployeeData.count {
let employee_id = fetchedEmployeeData[i].empID
if fetchedExpectedData[indexPath.section].employee_id == employee_id
{
cell.lblEmpName.text = fetchedEmployeeData[i].name
}
}
return cell
}
Check below points:-
Make sure you registered tableview cell nib and added dataSource and Delegate.
You are reloading tableview after your fetchedExpectedData array filled
Just add the below code in viewDidLoad
expectedTableView.delegate = self
expectedTableView.datasource = self
also check if you have set UITableViewDelegate , UITableViewDataSource in starting of the controller
class Yourviewcontrollername: UIViewController,UITableViewDelegate,UITableViewDataSource
{
//Rest of the code
}
Also put breakpoint in all delegate methods and see if anything hits.
Related
Im receiving a JSON array from php and trying to passing data to table view. However, my tableview does not display the data.
class test1ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate {
var TableData:Array< String > = Array < String >()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return TableData.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! testTableViewCell
cell.mylabel1.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 as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
print(data!)
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
// print(json!)
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let countries_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let country_obj = countries_list[i] as? NSDictionary
{
if let name = country_obj["name"] as? String
{
if let age = country_obj["age"] as? String
{
TableData.append(name + age)
}
}
}
}
}
}
When the array gives initial values like
animals = ["hinno", "ali", "khalil"],
the values appear to custom cell, but when i take the data from a server and do the json conversion, nothing appears.
tableview.reloadData() any time you make changes to the array.
If reload Data of the collection or tableView doesn't work use that in Dispatch code like this
DispatchQueue.main.async {
yourTableViewName.reloadData()
}
I am trying to retrieve data from my site, I am using Alamofire, how can I put that data into an array that I can use to populate my table view?
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request("http://lytestech.ga/api/lytes/get_movies/").responseJSON { response in
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
let res = json as! NSDictionary
let movies = res["movies"] as! NSArray
// movieTitles = movies["movie_desc"]
let movieTitles: [String] = movies["movietitile"] as! String
print (movies)
print (movieTitles)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
}
json data
JSON: {
movies = (
{
id = 66;
"movie_desc" = "spiders bite";
movietitile = spiderman;
},
{
id = 64;
"movie_desc" = horror;
movietitile = mummy;
}
);
status = ok;
}
(
{
id = 66;
"movie_desc" = "spiders bite";
movietitile = spiderman;
},
{
id = 64;
"movie_desc" = horror;
movietitile = mummy;
}
)
Store movies in movies NSArray
var movies = NSArray()
After that in cellForRowAt method you can display data like this.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier") as! YouCustomCell
let movieDetail = movies[indexPath.row] as! NSDictionary
cell.lblMovieName.text = movieDetail.value(forKey: "movietitile") as? String
return cell
}
Note: - This is just code skeleton, you can use as per your custom cell and Outlets
var movies:[Dictionary<String,AnyObject>] = [] // Makes movies array global
movies = res["movies"] // and tableview reload
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "cell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ??
UITableViewCell(style: .default, reuseIdentifier: identifier)
cell.textLabel!.text = movies[indexPath.row]["movietitile"] as? String
return cell
}
func demo()
{
let str : String = "http://lytestech.ga/api/lytes/get_movies/"
let url = NSURL(string:str)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(request)
.responseString { response in
switch (response.result) {
case .Success(let JSON):
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding)!
do {
let responseString = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
// print(responseString!)
self.movieName = []
self.desc = []
let arr = responseString!["movies"] as! NSArray
for j in 0..<arr.count{
let dic = arr[j] as! NSMutableDictionary
self.movieName.addObject(dic.valueForKey("movietitile")!)
self.desc.addObject(dic.valueForKey("movie_desc")!)
}
self.removeIndicator()
self.contactTable.reloadData()
} catch _ as NSError {
//print(error)
}
break
case .Failure:
print("FAILURE")
self.removeIndicator()
break
}
}
}
Convert your response Data into Dictionary
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: response.data) as! [String : Any]
Extract your Array from Dictionary , there is key name movies
if let arryMovies1 = dictionary["movies"] as? [[String:Any]] {
print (arryMovies1);
// Now your have your Array
// You can Populate into UItableView
// when your array is modified than you have to reload the tableData
self.arryMovies=arryMovies1
self.tableView.reloadData()
}
In your cellForRowAtIndexPath for populating in list view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "you_cell_identifre") as! UITableCell
let dicMovie = self.arryMovies[indexPath.row] as! NSDictionary
cell.lableTitle.text = dicMovie.value(forKey: "movietitile") as? String
return cell
}
I hope this will help you
I am new to Swift programming
SearchBar controller with tableview. I want display the multiple students in table view its working fine. I can add the search bar controller to table view and display the particular students data. table view cell contains the student information and image I want display particular student after search
this is the code
#IBOutlet var SearchBarDisp:UISearchBar!
override func viewDidLoad()
{
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
}
func updateSearchResults(for searchController: UISearchController) {
//todo
}
I can get student data from json
func getKids(url : String) {
UIApplication.shared.beginIgnoringInteractionEvents()
var errorCode = "1"
var msg = "Failed"
var request = URLRequest(url: URL(string: "getstaffstudents",
relativeTo: URL(string: serverURL+"/rkapi/api/"))!)
let session = URLSession.shared
request.httpMethod = "POST"
let bodyData = "staffId=\(staffId)"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = session.dataTask(with:request,completionHandler:{(d,response,error)in
do{
if let data = d {
if let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
errorCode = String(describing: jsonData["errorCode"]!)
msg = jsonData["msg"] as! String
print("msg values",msg)
if errorCode == "0" {
if let kid_list = jsonData["students"] as? NSArray {
for i in 0 ..< kid_list.count {
if let kid = kid_list[i] as? NSDictionary {
kidHoleData.removeAll()
let imageURL = url+"/images/" + String(describing: kid["photo"]!)
self.kidsData.append(Kids(
studentId: kid["studentId"] as? String,
name:kid["name"] as? String,
classId : kid["classId"] as? String,
standard: ((kid["standard"] as? String)! + " " + (kid["section"] as? String)!),
photo : (imageURL),
school: kid["schoolName"] as? String,
schoolId : "1",
url : url)
)
}
}
self.loopCount += 1
self.do_table_refresh()
}
} else {
self.displayAlert("Kids", message: msg)
}
} else {
self.displayAlert("Kids", message: "Data Not Available. Please try again")
}
}else {
self.displayAlert("Kids", message: "Please try again")
}
} catch let err as NSError {
print("JSON Error \(err)")
}
})
task.resume()
}
Table view
func numberOfSections(in tableView: UITableView) -> Int {
return (kidsData.count == 0) ? 0 : 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return kidsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(
withIdentifier: "Kidscell", for: indexPath) as! KidsTableViewCell
let maskLayer = CAShapeLayer()
let bounds = cell.bounds
maskLayer.path = UIBezierPath(roundedRect: CGRect(x: 3, y: 3, width: bounds.width-15, height: bounds.height-15), cornerRadius: 2).cgPath
cell.layer.mask = maskLayer
let row = (indexPath as NSIndexPath).row
if(kidsData.count>0){
let kid = kidsData\[row\] as Kids
cell.kidNameLabel.text = kid.name
cell.classLabel.text = kid.standard
cell.kidNameLabel.lineBreakMode = .byWordWrapping
cell.kidNameLabel.numberOfLines = 0
cell.kidImageView.image = UIImage(named: "profile_pic")
cell.kidImageView.downloadImageFrom(link: kid.photo!, contentMode: UIViewContentMode.scaleAspectFit) //set your image from link array.
}
return cell
}
I want display particular student in table view(like if I can search student name as vani it's display the student vani in table view) pls help me
copy the hole data in to the attendanceInfoDupilicate
var attendanceInfoDupilicate = [AttendanceInfo]()
Inside of the Json service call at end
self.attendanceInfoDupilicate = self.attendanceInfo
updater the search controller
func updateSearchResults(for searchController: UISearchController)
{
let searchToSeatch = AttendanceSearchBarController.searchBar.text
if(searchToSeatch == "")
{
self.attendanceInfo = self.attendanceInfoDupilicate
}
else{
self.attendanceInfo.removeAll()
let AttedanceData = self.attendanceInfoDupilicate
var kidsArray = [String]()
for AttendanceInfo in AttedanceData
{
kidsArray.append(AttendanceInfo.name)
if(AttendanceInfo.name.range(of: searchToSeatch!, options: .caseInsensitive) != nil)
{
self.attendanceInfo.append(AttendanceInfo)
}
}
}
self.TableView.reloadData()
}
I already new in swift 3 and objetive c, right now I am stuck into how can I pass the id of each row to another table view controller when the user tap in the row the user want to go.
Here is the json data firstFile:
[
{"id_categoria":"1","totalRows":"323","nombre_categoria":"Cirug\u00eda"},
{"id_categoria":"2","totalRows":"312","nombre_categoria":"Med Interna"},
{"id_categoria":"3","totalRows":"6","nombre_categoria":"Anatomia"},
{"id_categoria":"4","totalRows":"24","nombre_categoria":"Anestesiologia"},
...]
Here is my first table view controller:
import UIKit
class CatMedVC: UIViewController, UITableViewDataSource {
#IBAction func volver(_ sender: Any) { }
#IBOutlet weak var listaCategoria: UITableView!
var fetchedCategoria = [Categoria]()
override func viewDidLoad() {
super.viewDidLoad()
listaCategoria.dataSource = self
parseData()
}
override var prefersStatusBarHidden: Bool{
return true
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedCategoria.count
}
public func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) ->
UITableViewCell {
let cell = listaCategoria.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = fetchedCategoria[IndexPath.row].esp
cell?.detailTextLabel?.text = fetchedCategoria [IndexPath.row].totalRows
return cell!
}
func parseData() {
let url = "http://www.url.com/firstFile.php" //in json format
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil) {
print("Error")
}
else {
do {
let fetchedData = try JSONSerialization.jsonObject(with:data!, options: .mutableLeaves) as! NSArray
//print(fetchedData)
for eachFetchedCategoria in fetchedData {
let eachCategoria = eachFetchedCategoria as! [String : Any]
let nombre_categoria = eachCategoria["nombre_categoria"] as! String
let totalRows = eachCategoria["totalRows"] as! String
let id_categoria = eachCategoria["id_categoria"] as! String
self.fetchedCategoria.append(Categoria(nombre_categoria: nombre_categoria, totalRows: totalRows, id_categoria: id_categoria))
}
//print(self.fetchedCategoria)
self.listaCategoria.reloadData()
}
catch {
print("Error 2")
}
}
}
task.resume()
}
}
class Categoria {
var nombre_categoria : String
var totalRows : String
var id_categoria : String
init(nombre_categoria : String, totalRows : String, id_categoria : String) {
self.nombre_categoria = nombre_categoria
self.totalRows = totalRows
self.id_categoria = id_categoria
}
}
So I need pass the id_categoria String into the another table view to show the data for the id selected previously...here I don't know how to do it...I have the json file waiting for the id selected previously..but I don't know how to catch it into the url
Here the second table view:
import UIKit
class EspMedVC: UITableViewController {
var TableData:Array< String > = Array < String >()
var EspecialidadArray = [String]()
#IBAction func volver(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.url.com/secondFile.php?id=") // Here I need to put the id_categoria String in json format
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", 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 as 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?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let nombre_especialidad = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let nombre_esp_obj = nombre_especialidad[i] as? NSDictionary
{
if let nombre_especialidad = nombre_esp_obj["subesp"] as? String
{
if let totalRows = nombre_esp_obj["totalRows"] as? String
{
TableData.append(nombre_especialidad + " [" + totalRows + "]")
}
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
self.tableView.reloadData()
}
}
This is a rough guide, please search for the methods in the documentation or here at other questions inside stackoverflow.
1) Add a variable inside your EspMedVC that will hold the "id_categoria String" that should be displayed.
2) Add a variable inside your CatMedVC that will hold the "id_categoria String" that the user selected.
3) Implement the "didSelectRow" delegate method from your tableview inside the "CatMedVC", inside this method you should set the variable set on step 2.
4) Implement the "prepareForSegue" method inside your CatMedVC, inside the the implementation you should retrieve the destination VC, cast it to "EspMedVC" and set the variable from step 1.
5) On the "viewDidLoad" from EspMedVC you can now use the variable set on step 2 to query your JSON and update the table view accordingly.
I have the following two functions in my first ViewController. They load a UITableView with over 300 rows. I call the loadRemoteData function inside the ViewDidLoad. Everything works fine in the first ViewController.
// MARK: - parseJSON
func parseJSON(data: NSData) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
if let rootDictionary = json as? [NSObject: AnyObject], rootResults = rootDictionary["results"] as? [[NSObject: AnyObject]] {
for childResults in rootResults {
if let firstName = childResults["first_name"] as? String,
let lastName = childResults["last_name"] as? String,
let bioguideId = childResults["bioguide_id"] as? String,
let state = childResults["state"] as? String,
let stateName = childResults["state_name"] as? String,
let title = childResults["title"] as? String,
let party = childResults["party"] as? String {
let eachLegislator = Legislator(firstName: firstName, lastName: lastName, bioguideId: bioguideId, state: state, stateName: stateName, title: title, party: party)
legislators.append(eachLegislator)
}
}
}
} catch {
print(error)
}
}
// MARK: - Remote Data configuration
func loadRemoteData() {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let url = "https://somedomain.com/legislators?order=state_name__asc,last_name__asc&fields=first_name,last_name,bioguide_id"
if let url = NSURL(string: url) {
let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
if let error = error {
print("Data Task failed with error: \(error)")
return
}
if let http = response as? NSHTTPURLResponse, data = data {
if http.statusCode == 200 {
dispatch_async(dispatch_get_main_queue()) {
self.parseJSON(data)
self.tableView.reloadData()
}
}
}
})
task.resume()
}
}
In the second ViewController, I want to display more information about the individual listed in the cell that is tapped, for that I use a different URL such as https://somedomain.com/legislators?bioguide_id=\"\(bioguideId)\" which provides me with a lot more detail. (The data being requested from the JSON Dictionary is different)
The code I use in the second ViewController is just like shown above with the only difference being the URL. I can print the url coming from the previous ViewController and it is displayed in the console log but no json data is shown.
I would appreciate any help.
Thanks
Below is the code for my second ViewController:
import UIKit
class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var bioguideId: String?
var currentLegislator: Legislator? = nil
var currentLegislatorUrl: String?
let reuseIdentifier = "Cell"
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var tableView: UITableView!
// MARK: - parseJSON
private func parseJSON(data: NSData) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
if let rootDictionary = json as? [NSObject: AnyObject],
rootResults = rootDictionary["results"] as? [[NSObject: AnyObject]] {
for childResults in rootResults {
if let firstName = childResults["first_name"] as? String,
let lastName = childResults["last_name"] as? String,
let bioguideId = childResults["bioguide_id"] as? String,
let state = childResults["state"] as? String,
let stateName = childResults["state_name"] as? String,
let title = childResults["title"] as? String,
let party = childResults["party"] as? String {
currentLegislator = Legislator(firstName: firstName, lastName: lastName, bioguideId: bioguideId, state: state, stateName: stateName, title: title, party: party)
}
}
}
} catch {
print(error)
}
}
// MARK: - Remote Data configuration
func loadRemoteData(url: String) {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let url = currentLegislatorUrl
if let url = NSURL(string: url!) {
let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
if let error = error {
print("Data Task failed with error: \(error)")
return
}
print("Success")
if let http = response as? NSHTTPURLResponse, data = data {
if http.statusCode == 200 {
dispatch_async(dispatch_get_main_queue()) {
self.parseJSON(data)
self.tableView.reloadData()
}
}
}
})
task.resume()
}
}
func loadImage(urlString:String) {
let imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if (error == nil && data != nil) {
func display_image() {
self.imageView.image = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
print(currentLegislatorUrl!)
loadRemoteData(currentLegislatorUrl!)
loadImage("https://theunitedstates.io/images/congress/225x275/\(bioguideId!).jpg")
self.title = bioguideId
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath)
cell.textLabel!.text = currentLegislator?.firstName
return cell
}
}
Thanks to Adam H. His comment made me reevaluate the URL I was using and by adding additional operators, now the data is shown in my second ViewController.