2017-02-04 184 views
1

我已經在單獨的ViewController類中實現了兩個UITableview。在成功添加第二個UItableView的代碼後,我的項目會生成,但加載後會停止。UITableView崩潰在tableview.datasource開始

它停止了紅線:

tableView.delegate.dataSource = self 

隨着讀取錯誤:

Thread 1 EXEC_BAD_INSTRUCTION (code-EXC_i386_INVOP,subcode=0x0)

fatal error: unexpectedly found nil while unwrapping an Optional value

因爲這並沒有發生,直到將第二在第二個視圖控制器中的UItableview我想知道如果我的代碼可能彼此衝突。我將發佈兩個視圖控制器的副本。我應該改變什麼?

順便說一句:FilmsViewController是應用程序崩潰的地方。雖然它的工作將MCViewController電影之前:

B:

class FilmsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
    weak var tableView : UITableView! 
    var FilmArray = [String]() 

    let film_url = "https://www.testing.com/api/resources/films/1" 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return FilmArray.count 
    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


     let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for:indexPath) as! FilmsAPITableViewCell 
     // Configuring Cell 
     cell.movieTitle.text = FilmArray[indexPath.row] 
     // Returning the cell 
     return cell 
    } 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.dataSource = self 
     tableView.delegate = self 
     let url:URL = URL(string: film_url)! 
     let session = URLSession.shared 

     let request = NSMutableURLRequest(url: url) 
     request.httpMethod = "GET" 
     request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY") 
     request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization") 
     request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData 
     let paramString = "" 

     request.httpBody = paramString.data(using: String.Encoding.utf8) 

     let task = session.dataTask(with: request as URLRequest, completionHandler: { 
      (
      data, response, error) in 

      guard let _:Data = data, let _:URLResponse = response , error == nil else { 

       return 
      } 



      var json:Any? 

      do 
      { 
       if let existingData = data { 
        json = try JSONSerialization.jsonObject(with: existingData, options: []) 
       } 

       // Prasing JSON 
       if let parsedData = json as? [[String:Any]] { 
        for dict in parsedData { 
         if let title = dict["title"] as? String { 
          self.FilmArray.append(title) 
          print(json) 
         } 
        } 

        OperationQueue.main.addOperation({ 
         self.tableView.reloadData() 
        }) 
       } 
      } 
      catch 
      { 
       return 
      } 

      guard let server_response = json as? NSDictionary else 
      { 
       return 
      } 

      if let data_block = server_response["data"] as? NSDictionary 
      { 
       if let session_data = data_block["session"] as? String 
       { 
        // self.login_session = session_data 

        let preferences = UserDefaults.standard 
        preferences.set(session_data, forKey: "session") 

        // DispatchQueue.main.async(execute: self.LoginDone) 
       } 
      } 
     }) 

     task.resume() 

     // Do any additional setup after loading the view. 
    } 

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



} 

MC:

class MCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    let message_url = "https://www.testing.com/api/resources/get_film_message/film_id/3825" 
    let send_url = "https://www.testing.com/api/resources/send_film_message" 
    let film_id = "3825" 
    var messageArray = [String]() 
    weak var tableView : UITableView! 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return messageArray.count 
    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


     let cell = tableView.dequeueReusableCell(withIdentifier: "msgContent", for:indexPath) as! MessageTableViewCell 
     // Configuring Cell 
     cell.msgContent.text = messageArray[indexPath.row] 
     // Returning the cell 
     return cell 
    } 



    @IBOutlet weak var MessageInput: UITextField! 
    @IBAction func Sendmsg(_ sender: Any) { 
     Sendmsg(username:MessageInput.text!, password: film_id) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.dataSource = self 
     tableView.delegate = self 
     // Do any additional setup after loading the view. 
     //let post_data: NSDictionary = NSMutableDictionary() 


     //  post_data.setValue(username, forKey: "username") 
     //  post_data.setValue(password, forKey: "password") 

     let url:URL = URL(string: message_url)! 
     let session = URLSession.shared 

     let request = NSMutableURLRequest(url: url) 
     request.httpMethod = "GET" 
     request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY") 
     request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization") 
     request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData 
     // Do any additional setup after loading the view. 
     var paramString = "" 


     //  for (key, value) in post_data 
     //  { 
     //   paramString = paramString + (key as! String) + "=" + (value as! String) + "&" 
     //  } 
     // 
     request.httpBody = paramString.data(using: String.Encoding.utf8) 

     let task = session.dataTask(with: request as URLRequest, completionHandler: { 
      (
      data, response, error) in 

      guard let _:Data = data, let _:URLResponse = response , error == nil else { 

       return 
      } 



      let json: Any? 

      do 
      { 
       json = try JSONSerialization.jsonObject(with: data!, options: []) 
       if let parsedData = json as? [[String:Any]] { 
        for dict in parsedData { 
         if let title = dict["message"] as? String { 
          self.messageArray.append(title) 
          print(json) 
         } 
        } 
       } 
      } 
      catch 
      { 
       return 
      } 

      guard let server_response = json as? NSDictionary else 
      { 
       return 
      } 


      if let data_block = server_response["data"] as? NSDictionary 
      { 
       if let session_data = data_block["session"] as? String 
       { 
        // self.login_session = session_data 

        let preferences = UserDefaults.standard 
        preferences.set(session_data, forKey: "session") 

        // DispatchQueue.main.async(execute: self.LoginDone) 
       } 
      } 



     }) 

     task.resume() 
    } 

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

    func Sendmsg(username:String, password:String) 
    { 
     let post_data: NSDictionary = NSMutableDictionary() 


     post_data.setValue(username, forKey: "message") 
     post_data.setValue(password, forKey: "film_id") 

     let url:URL = URL(string: send_url)! 
     let session = URLSession.shared 

     let request = NSMutableURLRequest(url: url) 
     request.httpMethod = "POST" 
     request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY") 
     request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization") 
     request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData 

     var paramString = "" 


     for (key, value) in post_data 
     { 
      paramString = paramString + (key as! String) + "=" + (value as! String) + "&" 
     } 

     request.httpBody = paramString.data(using: String.Encoding.utf8) 

     let task = session.dataTask(with: request as URLRequest, completionHandler: { 
      (
      data, response, error) in 

      guard let _:Data = data, let _:URLResponse = response , error == nil else { 

       return 
      } 



      let json: Any? 

      do 
      { 
       json = try JSONSerialization.jsonObject(with: data!, options: []) 
       print(json) 
      } 
      catch 
      { 
       return 
      } 

      guard let server_response = json as? NSDictionary else 
      { 
       return 
      } 


//   if let data_block = server_response["data"] as? NSDictionary 
//   { 
//    if let session_data = data_block["session"] as? String 
//    { 
//     self.login_session = session_data 
//      
//     let preferences = UserDefaults.standard 
//     preferences.set(session_data, forKey: "session") 
//      
//     DispatchQueue.main.async(execute: self.LoginDone) 
//    } 
//   } 
//    


     }) 

     task.resume() 


    } 


    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    // Get the new view controller using segue.destinationViewController. 
    // Pass the selected object to the new view controller. 
    } 
    */ 

} 

回答

0

你在哪裏初始化tableView?好像它可能是nil ....

tableView = UITableView(frame: frame)

如果你使用的情節提要/廈門國際銀行,你還可以連接tableView了作爲IBOutlet

+0

tableView = UITableView(frame:frame)?我不確定我在呼喚它。你能多解釋一下嗎? –

+0

我應該在哪裏調用它? –

+0

在做其他事情之前,我會在'viewDidLoad'中調用它。 'frame'參數將是一個CGRect,它具有你想要的x,y位置和寬度,高度。雖然我會小心地根據viewDidLoad中的視圖框架來設置框架,因爲視圖的框架還沒有被計算出來。 'viewDidLoad'中的tableView = UITableView()'然後'tableView.frame = CGRect(x:yourX,y:yourY,width:yourWidth,height:yourHeight)''viewDidAppear'中的其他地方也是一個可行的選項。 – Samantha