2017-02-19 4 views
0

Я делаю табличный вид с каналами внутри него, которые пользователи могут использовать, чтобы попасть в этот канал. Когда пользователь прослушивает этот канал, я хочу получить идентификатор и имя канала из firebase. Следующая функция должна работать, но это не так. Выполняется сама подготовка к функции segue, но не if if let channel = sender as? Канал {// не выполняется}. Поэтому я не вижу «выполненную» печать.Функция внутри prepareForSegue не будет выполнена

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    super.prepare(for: segue, sender: sender) 
     if let channel = sender as? Channel { 
     print("executed") 
     let chatVc = segue.destination as! channelMultiplayerViewController 
     chatVc.channel = channel 
     chatVc.channelRef = channelRef.child(channel.id) 
    } 
} 

Это мой полный код, если вам это нужно:

import UIKit 
import Firebase 
import Foundation 

enum Section: Int { 
    case createNewChannelSection = 0 
    case currentChannelsSection 
} 

extension multiplayerChannelView: UISearchResultsUpdating { 
    func updateSearchResults(for searchController: UISearchController) { 
     filterContentForSearchText(searchText: searchController.searchBar.text!) 
    } 
} 

class multiplayerChannelView: UITableViewController { 


    // MARK: Properties 
    var channels: [Channel] = [] 
    let searchController = UISearchController(searchResultsController: nil) 
    var filteredChannels = [Channel]() 
    private lazy var channelRef: FIRDatabaseReference = FIRDatabase.database().reference().child("channels") 
    private var channelRefHandle: FIRDatabaseHandle? 
    var senderDisplayName: String? 
    var newChannelTextField: UITextField? 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     title = "Rooms" 
     observeChannels() 
     searchController.searchResultsUpdater = self 
     searchController.dimsBackgroundDuringPresentation = false 
     definesPresentationContext = true 
     tableView.tableHeaderView = searchController.searchBar 
    } 
    deinit { 
     if let refHandle = channelRefHandle { 
      channelRef.removeObserver(withHandle: refHandle) 
     } 
    } 
    func filterContentForSearchText(searchText: String, scope: String = "All") { 
     filteredChannels = channels.filter { Channel in 
      return (Channel.name.lowercased().range(of: searchText.lowercased()) != nil) 
     } 

     tableView.reloadData() 
    } 
    @IBAction func createChannel(_ sender: AnyObject) { 
     if let name = newChannelTextField?.text { 
      let newChannelRef = channelRef.childByAutoId() 
      let channelItem = [ 
       "name": name 
      ] 
      newChannelRef.setValue(channelItem) 
     } 
    } 

    override func viewDidAppear(_ animated: Bool) { 
     super.viewDidAppear(animated) 
    } 
    private func observeChannels() { 
     channelRefHandle = channelRef.observe(.childAdded, with: { (snapshot) -> Void in // 1 
      let channelData = snapshot.value as! Dictionary<String, AnyObject> // 2 
      let id = snapshot.key 
      if let name = channelData["name"] as! String!, name.characters.count > 0 { 
       self.channels.append(Channel(id, name: name)) 
       self.tableView.reloadData() 
      } else { 
       print("Error! Could not decode channel data") 
      } 
     }) 
    } 

    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 2 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if let currentSection: Section = Section(rawValue: section) { 
      switch currentSection { 
      case .createNewChannelSection: 
       return 1 

      case .currentChannelsSection: 
       if searchController.isActive && searchController.searchBar.text != "" { 
        return filteredChannels.count 
       } 
       else{ 
        return channels.count 
       } 
      } 
     } else { 
      return 0 
     } 
    } 
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let reuseIdentifier = (indexPath as NSIndexPath).section == Section.createNewChannelSection.rawValue ? "NewChannel" : "ExistingChannel" 
     let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) 

     if (indexPath as NSIndexPath).section == Section.createNewChannelSection.rawValue { 
      if let createNewChannelCell = cell as? CreateChannelCell { 
       newChannelTextField = createNewChannelCell.newChannelNameField 
      } 
     } else if (indexPath as NSIndexPath).section == Section.currentChannelsSection.rawValue { 
      if searchController.isActive && searchController.searchBar.text != "" { 
       cell.textLabel?.text = filteredChannels[(indexPath as NSIndexPath).row].name 
      } else { 
       cell.textLabel?.text = channels[(indexPath as NSIndexPath).row].name 
      } 
     } 

     return cell 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     super.prepare(for: segue, sender: sender) 
      if let channel = sender as? Channel { 
      print("executed") 
      let chatVc = segue.destination as! channelMultiplayerViewController 
      chatVc.channel = channel 
      chatVc.channelRef = channelRef.child(channel.id) 
     } 
    } 

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     if indexPath.section == Section.currentChannelsSection.rawValue { 
      var channel = channels 
      if searchController.isActive && searchController.searchBar.text != "" { 
       channel = [filteredChannels[(indexPath as NSIndexPath).row]] 
        } 
      else 
      { 
       channel = [channels[(indexPath as NSIndexPath).row]] 
      } 

      self.performSegue(withIdentifier: "ShowChannel", sender: channel) 
     } 
    } 

} 

Это .swift файл типа канала

import Foundation 

class Channel: NSObject { 
    let id:String 
    let name:String 
    init (_ id:String, name:String){ 
     self.id = id 
     self.name = name 
    } 
} 

Спасибо!

+0

Вы уверены, что идентификатор и переход связать это правильно настроить в Interface Builder? – ystack

+0

Существует push-сегу «ShowChannel», который ссылается на другой контроллер представления, я думаю, что часть работает правильно. – Petravd1994

ответ

1

Я ответил на ваш последний пост, а также, но Вы отправляете массив каналов

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    super.prepare(for: segue, sender: sender) 
     if let channel = sender as? Channel { 
     print("executed") 
     let chatVc = segue.destination as! channelMultiplayerViewController 
     chatVc.channel = channel 
     chatVc.channelRef = channelRef.child(channel.id) 
    } 
} 

Так блок - если позволить канал = отправителя как? Канал - не будет работать.

Изменить код выбора ячейки для:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if indexPath.section == Section.currentChannelsSection.rawValue { 
     if searchController.isActive && searchController.searchBar.text != "" { 
      let channel = filteredChannels[indexPath.row] 
      self.performSegue(withIdentifier: "ShowChannel", sender: channel) 
       } 
     else 
     { 
      let channel = channels[indexPath.row] 
      self.performSegue(withIdentifier: "ShowChannel", sender: channel) 
     } 
    } 
} 
+0

Такая же проблема здесь, я не получаю печать «выполнена». когда я печатаю (канал) сразу после self.performSegue, я получаю это: [], поэтому не идентификатор и имя, как должно быть – Petravd1994

+0

Я получил его, наконец, работать ... спасибо! ! – Petravd1994

Смежные вопросы