Последовательные объявления в строке должны быть разделены '; - PullRequest
0 голосов
/ 03 апреля 2020
 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)
  }

я получаю Последовательные объявления в строке должны быть разделены '; ошибка от config.stripMobilePayload = false; и пусть 'объявления не могут быть вычисляемыми свойствами, я пытаюсь создать приложение для чата с использованием pubnub, но я получаю так много ошибок, которые, похоже, не могу найти решения, поскольку я получил код в Интернете, поскольку я все еще учусь, https://www.pubnub.com/blog/how-to-build-ios-mobile-group-chat-app-swift-5-pubnub/ Я получил это отсюда, но я получаю много ошибок, даже после того, как следую за этим шаг за шагом.

1 Ответ

0 голосов
/ 03 апреля 2020

Вы не можете выполнить код на верхнем уровне класса (в отличие от игровой площадки). Введите код в 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()
}
...