Search code examples
iosuitableviewswiftuinavigationcontrolleruinib

File manager with reuse of UIViewController when the data come from the network


please help! I'm trying to implement a file manager that works with web server I have a UITableView with custom cell from .xib and I'm using this code to register cell

        self.tableView.registerNib (UINib (nibName: MaterialCell, bundle: nil), forCellReuseIdentifier: MaterialCell)

I have the same data, and so I want to use a UIViewController again and write in didSelectRowAtIndexPath here this code

var viewController = FloderViewController ()   self.navigationController! .pushViewController`

the problem is that I get the data from the network and when I try to re-use UIViewController I have an error

fatal error: unexpectedly found nil while unwrapping an Optional value

enter image description here

What am I doing wrong and how can I implement this! Thanks for any help  

EDIT:

This my code

import UIKit

class FloderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let Queue               = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
    let Main                = dispatch_get_main_queue()
    let CustomCell                = "CustomCell"

    //MARK: - Variables -
    var elements: Array<JSON>  = []

    //MARK: - IBOutlet -

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        getJSON("params", value: params!)
        self.tableView.registerNib(UINib(nibName: CustomCell, bundle: nil), forCellReuseIdentifier: CustomCell)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return elements.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(CustomCell, forIndexPath: indexPath) as CustomCellClass

        cell.name.text  = elements[indexPath.row]["name"].stringValue
        cell.autor.text = elements[indexPath.row]["autor"].stringValue
        cell.date.text = elements[indexPath.row]["date"].stringValue

        return cell
    }

    //MARK: - UITableViewDelegate -

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


            params = materials[indexPath.row]["folderPath"].stringValue
            var viewController = FloderViewController()
            self.navigationController!.pushViewController(viewController, animated: true)

    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100
    }

    func getJSON (key: NSString, value: AnyObject) {
        var request = HTTPTask()
        request.baseURL = BaseURL
        let params: Dictionary<String,AnyObject> = [key: value]
        var error: NSError?
        request.POST(OpenFolder, parameters: params, success: {(response: HTTPResponse) in
            if let data = response.responseObject as? NSData {
                var responseBeltJSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
                var json = JSON(responseBeltJSON!)
                elements = json["elements"].arrayValue
                dispatch_async(self.Main, {
                    self.tableView.reloadData()
                })
            }
            },failure: {(error: NSError, response: HTTPResponse?) in
                println("error: \(error)")
        })
    }

Solution

  • This line

    var viewController = FloderViewController ()

    Will create an instance of your FloderViewController but it isn't linked to a Storyboard or nib file, so unless you are creating all of the UI elements (including your tableView) programmatically the IBOutlets will be nil - as you are seeing.

    If you are using a storyboard then you should create your view controller like this -

    let viewController = self.storyboard.instantiateViewControllerWithIdentifier("floderVCId") as FloderViewController // Identifier must match the scene identifier in the storyboard
    self.presentViewController(viewController, animated: true, completion: nil)