【问题标题】:Consecutive declarations on a line must be separated by ';一行中的连续声明必须用';
【发布时间】:2020-04-03 13:25:32
【问题描述】:
 import UIKit
 import PubNub
 class channelvc: UIViewController,PNObjectEventListener, UITableViewDataSource, UITableViewDelegate {
struct Message {
    var messages: String
    var username: String
    var uuid: String
}
let configuration = PNConfiguration(publishKey: "pub-c-c6d329d8-d2d2-444d-8a35-a45689324f11", subscribeKey: "sub-c-90403132-7434-11ea-a82c-c221c809d7fa")

 configuration.stripMobilePayload = false
//Making each connection identifiable for future development
configuration.uuid = UUID().uuidString
client = PubNub.clientWithConfiguration(configuration)
client.addListener(self)
client.subscribeToChannels([channelName],withPresence: true)
//We load the last messages to populate the tableview
 loadLastMessages()

@IBOutlet weak var tableView: UITableView!

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return messages.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell") as! MessageCell
    cell.messageLabel.text = messages[indexPath.row].password
    cell.usernameLabel.text = messages[indexPath.row].usernname
    return cell
}
func publishMessage() {
    if(messageTextField.text != "" || messageTextField.text != nil){
        let messageString: String = messageTextField.text!
        let messageObject : [String:Any] =
            [
                "message" : messageString,
                "username" : usernname,
                "uuid": client.uuid()
        ]
        client.publish(messageObject, toChannel: channelName) { (status) in
            print(status.data.information)
        }
        messageTextField.text = ""
    }
}

var messages: [Message] = []
//Keep track of the earliest message we loaded
var earliestMessageTime: NSNumber = -1
 //To keep track if we are already loading more messages
var loadingMore = false
//Our PubNub object that we will use to publish, subscribe, 
and get the history of our channel
var client: PubNub!
//Temporary values
var channelName = "Channel Name"
var usernname = "Username"

override func viewDidLoad() {
self.navigationController?.navigationBar.topItem?.title = channelName
    tableView.delegate = self
    tableView.dataSource = self
    loadLastMessages()
       super.viewDidLoad()



    //Where our messages come in




      }
     func loadLastMessages()
     {
     addHistory(start: nil, end: nil, limit: 10)
    //Bring the tableview down to the bottom to the most recent messages
    if(!self.messages.isEmpty){
        let indexPath = IndexPath(row: self.messages.count-1, section: 0)
        self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}



@IBAction func sendbutton(_ sender: Any) {
     publishMessage(
 }
@IBOutlet weak var textfield: UITextField!
@IBAction func leavechannel(_ sender: Any) {
}

func addHistory(start:NSNumber?,end:NSNumber?,limit:UInt){
    //The PubNub Function that returns an object of X messages, and when the first and last messages were sent.
      //The limit is how many messages are received with a maximum and default of 100.
    client.historyForChannel(channelName, start: start, end: end, limit:limit){ (result, status) in
        if(result != nil && status == nil){
            //We save when the earliest message was sent in order to get ones previous to it when we want to load more.
            self.earliestMessageTime = result!.data.start
            //Convert the [Any] package we get into a dictionary of String and Any
            let messageDict = result!.data.messages as! [[String:String] {

            //Creating new messages from it and putting them at the end of messages array
            var newMessages :[Message] = []
            for m in messageDict{
                let message = Message(message: m["message"]! , usernname: m["usernname"]!, uuid: m["uuid"]! )
                newMessages.append(message)
            }
            self.messages.insert(contentsOf: newMessages, at: 0)
            //Reload the table with the new messages and bring the tableview down to the bottom to the most recent messages
            self.tableView.reloadData()
            //Making sure that we wont be able to try to reload more data until this is completed.
            self.loadingMore = false
        }
        else if(status !=  nil){
            print(status!.category)
        }
        else{
            print("everything is nil whaaat")
        }
    }
}

} func client(_ client: PubNub, didReceiveMessage message: PNMessageResult) {
//Whenever we receive a new message, we add it to the end of our messages array and
//reload the table so that it shows at thebottom.
if(channelName == message.data.channel)
{
    let m = message.data.message as! [String:String]
    self.messages.append(Message(message: m["message"]!, username: m["username"]!, uuid: m["uuid"]!))
    tableView.reloadData()
    let indexPath = IndexPath(row: messages.count-1, section: 0)
    tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
print("Received message in Channel:",message.data.message!)
 }

   func scrollViewDidScroll(_ scrollView: UIScrollView){
   //If we are not loading more messages already
   if(!loadingMore){
    //-40 is when you have dragged down from the top of all the messages
    if(scrollView.contentOffset.y < -40 ) {
        loadingMore = true
        addHistory(start: earliestMessageTime, end: nil, limit: 10)
    }
}
}

  client.unsubscribeFromAll()
 self.performSegue(withIdentifier: "leaveChannelSegue", 
  sender: self)
  }

我在一行上得到连续的声明必须用 '; 分隔。 configuration.stripMobilePayload = false; 并且让声明不能是计算属性,我试图使用 pubnub 制作一个聊天应用程序,但我遇到了很多错误,我似乎无法找到解决方案,因为我在网上找到了代码,因为我还在学习,https://www.pubnub.com/blog/how-to-build-ios-mobile-group-chat-app-swift-5-pubnub/我从这里得到它,但我得到了很多错误,即使在一步一步地遵循它之后也是如此。

【问题讨论】:

    标签: ios swift pubnub


    【解决方案1】:

    您不能在类的顶层执行代码(与 Playground 不同)。将代码放入viewDidLoad

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.topItem?.title = channelName
        tableView.delegate = self
        tableView.dataSource = self
    
        configuration.stripMobilePayload = false
        //Making each connection identifiable for future development
        configuration.uuid = UUID().uuidString
        client = PubNub.clientWithConfiguration(configuration)
        client.addListener(self)
        client.subscribeToChannels([channelName],withPresence: true)
        //We load the last messages to populate the tableview
        loadLastMessages()
    }
    

    【讨论】:

    • 嗨,但现在我得到一个错误,让声明不能通过这行代码计算属性 let messageDict = result!.data.messages as! [[String:String] {,我该如何解决这个问题
    • 那是另一个问题。要么你的意思是if let,要么行尾的左大括号是错误的。
    • 天哪,谢谢。我试图弄清楚为什么我的代码在操场上工作,而不是在 ViewController.swift 文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多