ios - 同时运行 Collection View 和 TableView 时应用程序崩溃。崩溃 :fatal error: unexpectedly found nil while unwrapping an Optional value

标签 ios swift uicollectionview

我有一个会水平滚动的 Collection View 。在该 Collection View 中,每个单元格单击 - 我必须在 TableView 中加载相应的数据。所以我将 TableView 放在 Collection View 下。

崩溃报告:

fatal error: unexpectedly found nil while unwrapping an Optional value

这是我的代码:

class HomeDiscoverViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var BTCollectionView: UICollectionView!

    @IBOutlet var DLTableView: UITableView!

    var BTdata = [BTData]()

    var Dealsdata = [DealsData]()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        ListBusinessTypes()
    }
// Values from Api for Business Types
    func ListBusinessTypes()
    {
        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

        let headers = ["x-access-token": token]

        let request = NSMutableURLRequest(URL: NSURL(string: "someurl")!,
                                          cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)

                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {
                        if let typeValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item in typeValues
                                {
                                    self.BTdata.append(BTData(json:item))
                                }
                            })
                        }
                        self.BTCollectionView.reloadData()
                    }
                    else
                    {
                        let message = json["message"] as? String

                        print(message)

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                }
            }
        })

        dataTask.resume()
    }

    // values from Api For Deals
    func ListDeals(BTId:String)
    {
        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

        let headers = [
            "cache-control": "no-cache",
            "postman-token": "1befe4c6-ec7c-ccb3-f537-97307f451807"
        ]

        let StringURL = "someurl"+token

        let request = NSMutableURLRequest(URL: NSURL(string: StringURL)!,
                                          cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {
                        if let DealsValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item  in DealsValues
                                {
                                    let itemObj = item as? Dictionary<String,AnyObject>

                                    let b_type = itemObj!["business_type"] as? String

                                    if(b_type == BTId)
                                    {
                                        self.Dealsdata.append(DealsData(json:item))
                                    }
                                }
                                self.DLTableView.reloadData()
                            })
                        }
                    }
                    else
                    {
                        let message = json["message"] as? String

                        print(message)

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }

                }

            }
        })

        dataTask.resume()
    }

    // Mark : Collection View Delegate and Datasource(Business Type)
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return BTdata.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell: DDLCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("BTCell", forIndexPath: indexPath) as! DDLCollectionCell
        cell.BTName.text = BTdata[indexPath.row].BTNames
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        ListDeals(BTdata[indexPath.row].BTIds!)
    }



    // Mark : Table View Delegate and Datasource(Deals)

    // count of search value and row value that are displaying
    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return self.Dealsdata.count
    }

    // number of rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 1
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell:DealsListTableCell = self.DLTableView.dequeueReusableCellWithIdentifier("cell") as! DealsListTableCell
        cell.DealName.text = Dealsdata[indexPath.row].DealNames
        cell.DealExpiryDate.text = Dealsdata[indexPath.row].DealAddresses
        return cell
    }

我在这里遇到 fatal error :

self.BTCollectionView.reloadData()

ListBusinessTypes() 方法下。我添加了所有委托(delegate)和数据源。但不知道我缺少什么。请帮助我。

谢谢。!!

最佳答案

add Exception Breakpoint from breakpoint navigator.

它会引导你解决问题。

关于ios - 同时运行 Collection View 和 TableView 时应用程序崩溃。崩溃 :fatal error: unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36856969/

相关文章:

Swift 枚举通过引用展开

ios - Swift 中的 URL 验证

swift - 在滚动期间点击时,UICollectionView 不再识别点击单元格?

ios - 有没有办法为 UICollectionView 中的特定部分应用自定义流布局?

android - 钛 ios 和 Android 中的自动完成文本字段

ios - 将选定的行复制到一个数组,该数组填充 Xcode 中的另一个 UITableView

ios - JSON AnyObject 到 Bool 的转换总是返回 nil

ios - 使 UIPickerView 依赖于选定的行(Swift)

Swift array.map - 无法调用 'map'

ios - CollectionView 以 UIScrollView 作为单元格