-3

I'm getting the following error in console:

fatal error: unexpectedly found nil while unwrapping an Optional value

And showing error in Xcode editor like following:

THREAD 1 EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0*0)

I have this code in Swift 3 for calling API and load it in view:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.nameLabel!.text = nameArray[indexPath.row]
    cell.dobLabel!.text = dobArray[indexPath.row]
    cell.descLabel!.text = descArray[indexPath.row]

    /*
    let imgURL = NSURL(string: imgURLArray[indexPath.row])
    let data = NSData(contentsOf: (imgURLArray as? URL)!)
    cell.imageView!.image = UIImage(data: data as! Data)
    */

    return  cell
}

And here is my TableViewCell file:

class TableViewCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel?
    @IBOutlet weak var descLabel: UILabel?
    @IBOutlet weak var dobLabel: UILabel?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
Anh Pham
  • 2,108
  • 9
  • 18
  • 29
sanjay rathod
  • 77
  • 1
  • 2
  • 16
  • Why do you use cell.nameLabel! as optional? Can you share the custom cell file. – Kapil G Jul 29 '17 at 06:30
  • Have you created your custom Cell class? – Kapil G Jul 29 '17 at 06:33
  • You force dereferencing your optionals with `!`, but if nil is embedded then you dereference nil pointer. Prefer using `?` with optional is the first basic rule if you don't feel easy with it. – Jean-Baptiste Yunès Jul 29 '17 at 06:33
  • How you specify number of rows post your code. – vp2698 Jul 29 '17 at 06:34
  • 1
    In which line? Please, don't make people guess, you're asking for help so it's your responsibility to give all necessary information. What answer did you check??? – meaning-matters Jul 29 '17 at 06:37
  • @sanjay rathod, I think you didn't set `outlet` reference of the `cell.namelabel...` to the variables in the class `TableViewCell`, or maybe the id of `cell` is not `"cell"`. – Tiefan Ju Jul 29 '17 at 06:40
  • Is your custom cell name is `TableViewCell` – Prashant Tukadiya Jul 29 '17 at 07:01
  • i had check this answer https://stackoverflow.com/questions/24948302/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value – sanjay rathod Jul 29 '17 at 07:06
  • 2
    Oh boy, don't use 4 separate arrays to store sets of 4 pieces of related data. Make a struct or an object that contains the 4 pieces of data, and have just one simple array of those structs/objects – Alexander Jul 29 '17 at 07:39
  • Possible duplicate of [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) – Keiwan Jul 29 '17 at 08:45
  • Can you try to put Exception Breakpoint, Swift breakpoint in Xcode and share the line at which the error occurs ? – Alen Alexander Jul 29 '17 at 10:17

1 Answers1

1

try to modify you ApiViewController and check with my code then see what happen

 import UIKit

 class ApiViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
    var nameArray = [String]()
    var dobArray = [String]()
    var imgURLArray = [String]()
    var descArray = [String]()
     var actorarray = NSArray()
    @IBOutlet weak var tableView: UITableView!

    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? NSDictionary {
            print(jsonObj!.value(forKey: "actors")!)

            actorarray = jsonObj!.value(forKey: "actors") as? NSArray

            self.tableView.reloadData()

        }
    }).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!)
        })
    }

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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

    let dic = self.actorarray[indexPath.row] as! NSDictionary


    cell.nameLabel!.text = dic.object(forKey: "name") as! String
    cell.dobLabel!.text = dic.object(forKey: "dob") as! String
    cell.descLabel!.text = dic.object(forKey: "image") as! String

    return  cell
 }
}
BHAVIK
  • 890
  • 7
  • 35