0

i'm quite new to Swift and i am currently having some problems with wrapping of optional values. My App is crashing after downloading the JSON from my Blog ( Download is working definitly ) with the error : fatal error: unexpectedly found nil while unwrapping an Optional value

I have no Idea how to fix this. Here is the Code:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!

var postsarray : [SDPost] = []
var hasloaded = false
var HUD = MBProgressHUD()

override func viewDidLoad() {
    super.viewDidLoad()

     self.tableView.register(UINib(nibName: "UICustomTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")

    HUD = MBProgressHUD.showAdded(to: self.view, animated: true)
    HUD.detailsLabel.text = "Daten werden geladen"
    HUD.label.text = "Moment bitte."

    self.tableView.register(TableCellTableViewCell.self, forCellReuseIdentifier: "cell")
}
override func viewDidAppear(_ animated: Bool) {
    let feed = SDFeedParser();
    let url = "www.pathtomyblog.net"

    tableView.isHidden = true
    feed.parseURL(url, success: { (Array:[Any]?, Int) in
        if (Array != nil)
        {
        self.postsarray = Array as! [SDPost]
        self.tableView.isHidden = false
        self.hasloaded = true
        self.tableView.reloadData()
        print("Data loaded.")
        }
        self.HUD.hide(animated: true, afterDelay: 0.1)
    }) { (Error) in
        print("Something went wrong." + (Error?.localizedDescription)!)
    }

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.postsarray.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell:TableCellTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! TableCellTableViewCell

    if (hasloaded){
    var post_info = SDPost()
    post_info = postsarray[indexPath.row]
    cell.articel_title.text = post_info.title;

    return cell
    }
    return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")
}

I hope you can help me. Best Regards and thanks in Advance!

chronikum
  • 716
  • 5
  • 12

1 Answers1

0

Firstly try to read about Swift language syntaxes. Usage of the force unwrap ! is quite dangerous if you are not checking what you are unwrapping or casting.

Try to use this basic language approaches:

if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
} else {
    print("Unable to retrieve the number of rooms.")
}

guard let image = UIImage(named: imageName) else { 
    return
}
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100