Todo 应用程序崩溃错误返回 NIL? xcode

Todo app crash error comes back with NIL? xcode

所以,我一直在构建这个项目,它是一个待办事项应用程序。当你点击一个单元格时,你的项目应该被搜索到 ask.com。我现在不断收到这个致命错误。正如您在我的代码中看到的那样,它在我的 "Appurl" 部分代码中显示为 nil。当我在代码中单击它时,它显示为 nil,这很奇怪。此外,它导致我的应用程序崩溃。源代码会很棒。我不知道如何解决这个问题。我所知道的是 nil 出现在 "Appurl" 出现的致命错误消息如下所示。我已经查找了此类致命错误消息的其他答案,但没有运气。 "thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

 import UIKit
  class NewTableViewController: UITableViewController, NewCellDelegate, {
var news:[News]!

override func viewDidLoad() {
    super.viewDidLoad()

    loadData()

    func loadData() {
        news = [News]()
        news = DataManager.loadAll(News.self).sorted(by: {[=11=].createdAt < .createdAt})
        self.tableView.reloadData()

    }

    @IBAction func Save(_ sender: Any) {
        let addAlert = UIAlertController(title: "ADD", message: "TODO", preferredStyle: .alert)
        addAlert.addTextField { (textfield:UITextField) in
            textfield.placeholder = "TODO"
        }

        addAlert.addAction(UIAlertAction(title: "Save", style: .default, handler: { (action:UIAlertAction) in
            guard let title = addAlert.textFields?.first?.text else {return}
            let newsave = News(title: title, completed: false, createdAt: Date(), itemIdentifier: UUID())
            newsave.saveItem()
            self.news.append(newsave)

            let indexPath = IndexPath(row: self.tableView.numberOfRows(inSection: 0), section: 0)

            self.tableView.insertRows(at: [indexPath], with: .automatic)


        }))

        addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.present(addAlert, animated: true, completion: nil)

    }

};

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

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return news.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NewTableViewCell
    cell.delegte = self

    let news = self.news[indexPath.row]

    cell.label.text = news.title

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        //getting the index path of selected row
        let indexPath = tableView.indexPathForSelectedRow

        //getting the current cell from the index path
        let currentCell = tableView.cellForRow(at: indexPath!) as! NewTableViewCell

        //getting the text of that cell
        let TODO = currentCell.label.text

     let appURL = NSURL(string: "https://www.ask.com/web?q=\
        (TODO))&o=0&qo=homepageSearchBox)")

    if UIApplication.shared.canOpenURL(appURL! as URL) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(appURL! as URL, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(appURL! as URL)
            }

        }
    }

您需要处理 url 字符串中出现的空格和特殊字符,例如 +

对于处理空格,

/**Handle occurance of space in given url string*/
class func handleSpaces(in urlString: String) -> String {
    return urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}

用于处理+符号,

/**Handle occurance of space in given url string*/
class func handlePlusSign(in urlString: String) -> String {
    return urlString.replacingOccurrences(of: "+", with: "%2B")
}

为避免崩溃,您需要在您的应用中使用适当的抗崩溃条件,例如 if letguard let

例如

if let url = appURL {
    // Proceed to use this url
}

您的代码将变为,

    let indexPath = tableView.indexPathForSelectedRow
    //getting the current cell from the index path
    guard let currentCell = tableView.cellForRow(at: indexPath!) as? NewTableViewCell else {
        print("Can't get your cell")
        return
    }
    //getting the text of that cell
    guard  let todo = currentCell.label.text else {
        print("Error in getting todo string")
        return
    }

    var urlString = "https://www.ask.com/web?q=\(todo))&o=0&qo=homepageSearchBox)"
    urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! // Handle spaces in your `todo` string.

    guard let appURL = URL(string: urlString) else {
        print("Can't form url")
        return
    }

    if UIApplication.shared.canOpenURL(appURL) {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(appURL)
        }
    }

谢谢。