0

The iOS app I develop consists two storyboards called Main.storyboard and Explore.storyboard which are merged using a UIBarButtonItem via a Storyboard Reference.

Main.StoryBoard UIBarButtonItem

Explore.storyboard consists a UIViewController where its class functions to call a REST API using json. Following is the code:

 import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    final let urlString = "http://tvshowapi.azurewebsites.net/tvshownewsfeed"
    @IBOutlet weak var tableView: UITableView!

    var nameArray = [String]()
    var favouriteCountArray = [String]()
    var imgURLArray = [String]()
    var contentArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadJsonWithURL()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func downloadJsonWithURL() {
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {

                for tvshow in jsonObj! {
                    if let name = tvshow["screenName"] as? String {
                        self.nameArray.append(name)
                    }
                    if let cnt = tvshow["favouriteCount"] as? Int {
                        self.favouriteCountArray.append("\(cnt)")
                    }
                    if let image = tvshow["imageUrl"] as? String {
                        self.imgURLArray.append(image)
                    }
                    if let content = tvshow["content"] as? String {
                        self.contentArray.append(content)
                    }
                }


                OperationQueue.main.addOperation({
                    self.tableView.reloadData() // CRASHES HERE
                })
            }
        }).resume()
    }

    func downloadJsonWithTask() {

        let url = NSURL(string: urlString)

        var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

        downloadTask.httpMethod = "GET"

        URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in

            let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

            print(jsonData!)

        }).resume()
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

        cell.nameLabel.textAlignment = .left
        cell.nameLabel.text = nameArray[indexPath.row]
        cell.dobLabel.text = favouriteCountArray[indexPath.row]

        let imgURL = NSURL(string: imgURLArray[indexPath.row])

        if imgURL != nil {
            let data = NSData(contentsOf: (imgURL as? URL)!)
            cell.imgView.image = UIImage(data: data as! Data)
        }

        return cell
    }

    ///for showing next detailed screen with the downloaded info
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        vc.imageString = imgURLArray[indexPath.row]
        vc.nameString = nameArray[indexPath.row]
        vc.dobString = favouriteCountArray[indexPath.row]
        vc.contentString = contentArray[indexPath.row]

        self.navigationController?.pushViewController(vc, animated: true)
    }
}

Explore.storyboard

At the runtime an error terminates the program with :

fatal error: unexpectedly found nil while unwrapping an Optional value

What am I doing wrong? What can I do to eliminate this error?

Honey
  • 24,125
  • 14
  • 123
  • 212
Heshan
  • 11
  • 3
  • 1
    is there specific line where following error occurs in code ? – idocode Mar 25 '17 at 14:18
  • See [What does “fatal error: unexpectedly found nil while unwrapping an Optional value” mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu?rq=1) – Honey Mar 25 '17 at 14:38
  • Yes, the error occurs within the downloadJsonWithURL() function at `self.tableView.reloadData()` – Heshan Mar 25 '17 at 14:43
  • the program is terminated with `EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)` at the above stated line – Heshan Mar 25 '17 at 14:52
  • @Heshan what stated line?!??? – Honey Mar 25 '17 at 14:57
  • 1
    Your code is pretty much error-prone: No error handling at all and multiple arrays as data source which is a no-go if optionals are involved. The error is probably related to Interface Builder (outlet not connected or custom class of cell not set). Further loading data synchronously in `cellForRow` with`NSData(contentsOf:` could cause very bad user experience. – vadian Mar 25 '17 at 15:35
  • @Honey `self.tableView.reloadData()` – Heshan Mar 25 '17 at 19:20
  • just as Vadian said. See [here](http://stackoverflow.com/questions/25986585/reloaddata-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-v) first. If it didn't work also see [here](http://stackoverflow.com/questions/27295894/reloaddata-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-va) – Honey Mar 25 '17 at 19:57
  • @Heshan did u see the links I mentioned? Did any of them help? – Honey Mar 27 '17 at 14:43
  • @Honey yes it was really helpful. I was able to eliminate the error. Thank you very much. – Heshan Mar 29 '17 at 17:00

0 Answers0