How to segue from a Table Cell View in Swift - ios

This is the code i have to far on the main table view view controller I just don't know how to go about transitioning to a new view controller to a selected cell to display more content about whatever cell was selected.
import UIKit
class MainVC: UITableViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var Table1: UITableView!
var postArray: [[String]] = []
var postSubject = ""
var postDescription = ""
var postDate = ""
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData() {
println("success1")
postArray = []
let httpMethod = "GET"
let timeout = 15
let urlAsString = "http://cgi.soic.indiana.edu/~team12/main_requests.php"
let url = NSURL(string: urlAsString)!
let urlRequest = NSMutableURLRequest(URL: url,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
urlRequest.HTTPMethod = httpMethod
let queue = NSOperationQueue()
println("success2")
NSURLConnection.sendAsynchronousRequest(urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
let html = NSString(data: data, encoding: NSUTF8StringEncoding)
} else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
if data.length > 0 && error == nil {
let html = NSString(data: data, encoding: NSUTF8StringEncoding)
var newArrayofDicts : NSMutableArray = NSMutableArray()
var arrayOfDicts : NSMutableArray? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:nil) as? NSMutableArray
println("successmutable")
if arrayOfDicts != nil {
for item in arrayOfDicts! {
if var dict = item as? NSMutableDictionary{
if dict["subject"] != nil{
self.postSubject = dict["subject"] as String
self.postDescription = dict["subject"] as String
self.postDate = dict["date"] as String
self.postArray.append([self.postSubject,self.postDescription,self.postDate])
println("successpost")
}
}
}
}
}
}
)
sleep(1)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
fetchData()
tableView.reloadData()
println("successanime")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println("successoverride")
let cell = tableView.dequeueReusableCellWithIdentifier("UpdateCell", forIndexPath: indexPath)
as UITableViewCell
println("successupdatecell")
cell.textLabel.text = postArray[indexPath.row][1]
cell.detailTextLabel?.text = postArray[indexPath.row][2]
println("success3")
return cell
}

Try this method
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
...
}
Or you can do it straight in the storyboard by ctrl dragging the prototype cell to the next viewController.
Hope this helps!!
Edit
If you want to segue to the next view controller programmatically, then you can do either:
performSegueWithIdentifier("yourSegueName", sender: nil)
Or:
presentViewController(nextViewController, animated: true, completion: nil)

Related

pass json id from one table view controller into another table view controller in swift 3

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.

viewcontroller conform to protocol "UITableViewDataSource, Video Mode Delegate"?

import UIKit
import Alamofire
protocol VideoModelDelegate{
func dataReady()
}
class VideoModel: NSObject {
let API_KEY = ""
let UPLOADS_PLAYLIST_ID = ""
var videoArray = [Video]()
var delegate:VideoModelDelegate?
func getFeedVideos() -> [Video] {
Alamofire.request(.GET, "",parameters: ["part":"snippet", "playlistId":UPLOADS_PLAYLIST_ID ,"key":API_KEY],
encoding: ParameterEncoding.URL, headers: nil).responseJSON {(response) -> Void in
if let JSON = response.result.value{
var arrayOfVideos = [Video]()
for video in JSON["items"] as! NSArray {
print(video)
let videoObj = Video()
videoObj.videoId = video.valueForKeyPath("snippet,resourceId, videoId")
String
videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
videoObj.videoDescription = video.valueForKeyPath("snippet.description") as!
String
videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
if self.delegate != nil {
self.delegate!.dataReady()
}
}
}
}
func getVideos() -> [Video] {
var videos = [Video]()
let video1 = Video()
video1.videoId = ""
video1.videoTitle = ""
videos.append(video1)
return videos
}
}
[Additional Errors][Error]1How to make my viewcontroller conform to protocol "UITableViewDataSource, and Video Mode Delegate"?
I have tried a number of suggested changes in the previous threads, but nothing got me through, Please help me out.
Thanks in advance
import UIKit
import Alamofire
class tab: UIViewController, UITableViewDataSource,
UITableViewDelegate, VideoModelDelegate ERROR- Type 'tab' does not conform to protocol 'UITableViewDataSource'
{
#IBOutlet weak var table: UITableView!
#IBOutlet weak var name: UILabel!
var videos : [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
//self.videos = model.getVideos()
model.getFeedVideos()
self.table.dataSource = self
self.table.delegate = self
/*Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").response { (req, res, data, error) -> Void in
print(res)
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(outputString)
}
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { response in
if let swiftyJsonVar = response.data
{
print("swiftyJsonvar:\(swiftyJsonVar)")
}
}*/
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.table.reloadData()
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func dataReady(){
self.videos = self.model.videoArray
self.table.reloadData()
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->
CGFloat {
return(self.view.frame.size.width / 320) * 180
}
func tableview(table:UITableView, numberOfRowsInSection section: Int ) ->Int{
return videos.count
}
func tableVie(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell = table.dequeueReusableCellWithIdentifier("jsonCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
//cell.textLabel?.text = videoTitle
let videoThumbnailUrlString =
videos[indexPath.row].videoThumbnailUrlString;)ERROR:Expected Expression
let videoThumbnailUrl != nil ERROR-'!= is not a prefix unary operator'
and 'Type annotation missing in pattern'
{
let request = NSURLRequest(URL: videoThumbnailUrl!)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
})
})
dataTask.resume()
}
return cell
func tableView(table: UITableView, didSelectRowAtIndexPath indexpath: NSIndexPath){
self.selectedVideo = self.videos[indexpath.row]
self.performSegueWithIdentifier("toVDVC", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let detailViewController = segue.destinationViewController as! VDViewController
detailViewController.selectedVideo = self.selectedVideo
}
}
}
}
re
It looks as though you haven't closed the method didReceivedMemoryWarning: and the tableview delegate methods are then effectively inside this method causing your issue. Add a closing bracket and it should be fine:
Update: Here is the updated code. There was some more formatting issues with brackets and an error with your if statement in the cellForRowAtIndex:
import UIKit
import Alamofire
class tab: UIViewController, UITableViewDataSource, UITableViewDelegate, VideoModelDelegate {
#IBOutlet weak var table: UITableView!
#IBOutlet weak var name: UILabel!
var videos : [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
//self.videos = model.getVideos()
model.getFeedVideos()
self.table.dataSource = self
self.table.delegate = self
/*Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").response { (req, res, data, error) -> Void in
print(res)
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(outputString)
}
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { response in
if let swiftyJsonVar = response.data
{
print("swiftyJsonvar:\(swiftyJsonVar)")
}
}*/
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.table.reloadData()
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} //ADDED CLOSING BRACKET HERE
func dataReady(){
self.videos = self.model.videoArray
self.table.reloadData()
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->
CGFloat {
return(self.view.frame.size.width / 320) * 180
}
func tableview(table:UITableView, numberOfRowsInSection section: Int ) ->Int{
return videos.count
}
func tableVie(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell = table.dequeueReusableCellWithIdentifier("jsonCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
//cell.textLabel?.text = videoTitle
//CHANGE THESE TWO LINES:
//let videoThumbnailUrlString = videos[indexPath.row].videoThumbnailUrlString;)
//if let videoThumbnailUrl != nil {
//TO THIS:
if let videoThumbnailUrl = videos[indexPath.row].videoThumbnailUrlString {
let request = NSURLRequest(URL: videoThumbnailUrl!)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
})
})
dataTask.resume()
}
return cell
}
func tableView(table: UITableView, didSelectRowAtIndexPath indexpath: NSIndexPath){
self.selectedVideo = self.videos[indexpath.row]
self.performSegueWithIdentifier("toVDVC", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let detailViewController = segue.destinationViewController as! VDViewController
detailViewController.selectedVideo = self.selectedVideo
}
}

didSelectRowAtIndexPath not being called

I am trying to use youtube api in ios swift, and following this tutorial http://www.appcoda.com/youtube-api-ios-tutorial/, but some how my didSelectRowAtIndexPath method is never being called.
Any suggestions will be helpful. Thanks
import UIKit
class SearchVideosViewController: UIViewController, UITableViewDataSource,UITableViewDelegate , UITextFieldDelegate{
#IBOutlet weak var wait: UIView!
#IBOutlet weak var tblShowVideoList: UITableView!
#IBOutlet weak var searchVideoText: UITextField!
var selectedVideoIndex:Int!
var videosArray: Array<Dictionary<NSObject,AnyObject>> = []
var apiKey = "my_api_key"
override func viewDidLoad() {
super.viewDidLoad()
searchVideoText.delegate = self
tblShowVideoList.delegate = self
tblShowVideoList.dataSource = self
wait.hidden = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videosArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
cell = tableView.dequeueReusableCellWithIdentifier("videolistcell", forIndexPath: indexPath)
let videoTitle = cell.viewWithTag(10) as! UILabel
let videoThumbnail = cell.viewWithTag(11) as! UIImageView
let videoDetails = videosArray[indexPath.row]
videoTitle.text = videoDetails["title"] as? String
videoThumbnail.image = UIImage(data: NSData(contentsOfURL: NSURL(string: (videoDetails["thumbnail"] as? String)!)!)!)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 140.0
}
// MARK: UITextFieldDelegate method implementation
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
wait.hidden = false
let type = "video"
// Form the request URL string.
var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(textField.text)&type=\(type)&key=\(apiKey)"
urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
// Create a NSURL object based on the above string.
let targetURL = NSURL(string: urlString)
// Get the results.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
// Convert the JSON data to a dictionary object.
do {
let resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! Dictionary<NSObject, AnyObject>
// Get all search result items ("items" array).
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i {
let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>
// Gather the proper data depending on whether we're searching for channels or for videos.
// Create a new dictionary to store the video details.
var videoDetailsDict = Dictionary<NSObject, AnyObject>()
videoDetailsDict["title"] = snippetDict["title"]
videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<NSObject, AnyObject>)["videoId"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(videoDetailsDict)
// Reload the tableview.
self.tblShowVideoList.reloadData()
}
} catch {
print(error)
}
}
else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel videos: \(error)")
}
// Hide the activity indicator.
self.wait.hidden = true
})
return true
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Selected row index \(indexPath.row)")
selectedVideoIndex = indexPath.row
performSegueWithIdentifier("playVideo", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "playVideo" {
let videosPlayerViewController = segue.destinationViewController as! VideosPlayerViewController
videosPlayerViewController.videoID = videosArray[selectedVideoIndex]["videoId"] as! String
}
}
// MARK: Custom method implementation
func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
let request = NSMutableURLRequest(URL: targetURL)
request.HTTPMethod = "GET"
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfiguration)
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
})
})
task.resume()
}
}
Try comments on:
searchVideoText.delegate = self

UITableView = nil, fatal error : unexpectedly found nil while unwrapping an Optional value

I got an error in self.tableView.reloadData(). Can it be because I use the SSASideMenu lib, where there are no segues between the menu and other views? To me, it seems like my tableView was not initialized.
class GroupListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var TableData:Array< String > = Array < String >()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")
title = "title"
var menuImage:UIImage = UIImage(named: "sidebtn")!
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "1", style: .Plain, target: self, action: "presentLeftMenuViewController")
menuImage = menuImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
self.navigationItem.leftBarButtonItem?.image = menuImage
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(url:String)
{
let httpMethod = "GET"
let timeout = 15
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
let json = NSString(data: data, encoding: NSASCIIStringEncoding)
self.extract_json(json!)
}else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
)
}
func extract_json(data:NSString)
{
var parseError: NSError?
let jsonData:NSData? = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &parseError)
if (parseError == nil)
{
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
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 + "]")
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh()
{
self.tableView.reloadData()
}
Ok. The exception you are getting is because your tableView is nil after viewdidLoad. It can be a connection problem, so first try this answer:
IBOutlet UITableView is null after View did load
Second, if all your nibs and are proper and you are still seeing this error. Then try the below code. [put tableview frame as you want]. This does everything you want to do programmatically and will work.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var TableData:Array< String > = Array < String >()
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")
tableView = UITableView(frame: self.view.frame)
title = "title"
var menuImage:UIImage = UIImage(named: "sidebtn")!
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "1", style: .Plain, target: self, action: "presentLeftMenuViewController")
menuImage = menuImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
self.navigationItem.leftBarButtonItem?.image = menuImage
self.view.addSubView(tableView)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(url:String)
{
let httpMethod = "GET"
let timeout = 15
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
let json = NSString(data: data, encoding: NSASCIIStringEncoding)
self.extract_json(json!)
}else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
)
}
func extract_json(data:NSString)
{
var parseError: NSError?
let jsonData:NSData? = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &parseError)
if (parseError == nil)
{
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
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 + "]")
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh()
{
self.tableView.reloadData()
}
}
In storyboard, find your tableviewcontroller, and right click on the tableview to check the referencing outlets, there are big chances under the referencing outlets, your defined your tableview variable not the same as the one you defined in your codes.
Then you just need to delete the referencing outlets of the tableview, also delete the codes "var tableView: UITableView!", then re-contorl drag the tableview to your code to make a new reference. It happened to me once for this reason.

table view not loading with swift

I have trouble in loading the table view when parsing json files in swift.
Parsing the data is doing well. But no data are displayed in the table view.
This is the code :
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var redditListTableView: UITableView!
var tableData = []
#IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
println("cancel")
}
#IBAction func done(sender: AnyObject) {
println("done")
}
override func viewDidLoad() {
super.viewDidLoad()
searchJsonFile("blabla.json")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println(tableData.count)
return tableData.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
let rowData: NSString = self.tableData[indexPath.row] as NSString
cell.textLabel.text = rowData as String
return cell
}
func searchJsonFile(searchFile: String) {
let urlPath = "http://data.../\(searchFile)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
var results = [String]()
if let results1 = jsonResult["data"] as? NSDictionary{
for (key, value) in results1 {
if let eng = value["eng"] as? NSDictionary {
if let name = eng["name"] as? NSString{
results.append(name)
}
}
}
}
//println(results) OK!!!!
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.redditListTableView.reloadData()
})
})
task.resume()
}
}
You are returning 0 from numberOfSectionsInTableView - so you get no data displayed. You want 1 section -
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
If you are not having sections then just remove this function or comment
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
or else return 1

Resources