0

채팅 구현을 위해 JSQMessageViewController를 사용하고 있습니다. json Post를 통해 메시지를 보내고받을 수 있습니다.JSQMessageViewController : 치명적인 오류 : 인덱스가 범위를 벗어났습니다.

오류없이 채팅 기록을로드 할 수 있습니다. 메시지를 검색하기 위해 사용 된 타이머 (5 초).

시간이 오래 걸리면 메시지가 5 초마다 다시로드됩니다.

잠시 후 갑자기 아래 줄에 "치명적인 오류 : 색인 범위 초과"가 표시됩니다. 아래

override func collectionView(_ collectionView: JSQMessagesCollectionView, messageDataForItemAt indexPath: IndexPath) -> JSQMessageData { 

    //app Crashes here : fatal error: Index out of range 
     return messages[indexPath.item] 


} 

가 = JSQMessage

CODE VAR 메시지 IS
var outgoingBubbleImageView:JSQMessagesBubbleImage! //= JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImage(with: UIColor.jsq_messageBubbleGreen()) 
var incomingBubbleImageView:JSQMessagesBubbleImage! //= JSQMessagesBubbleImageFactory().incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray()) 


var batchMessages = true 

// Refresh Messages 
var timer : Timer! 

// Don't double load! 
var isLoading = false 

override func viewDidLoad() { 
    super.viewDidLoad() 

    collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero 
    collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero 

    outgoingBubbleImageView = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImage(with: uicolorFromHex(0xDCF8C7)) 
    incomingBubbleImageView = JSQMessagesBubbleImageFactory().incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray()) //uicolorFromHex(0xF6F6F6) 


    let defaults = UserDefaults.standard 
    let usertype = defaults.object(forKey: "UserType") as! String 

    self.userType = usertype 

// self.getChatHistory (IPADDRESS + "/ VIOService.svc/JSONService/chatorderhistoryget /"+ EMAILID + "/"+ toEmail + "/" + ORDERID) // self.finishReceivingMessage()

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(addTapped)) 
    self.sender = userType 

    self.inputToolbar.contentView?.leftBarButtonItem = nil 


    // This is a beta feature that mostly works but to make things more stable it is diabled. 
    collectionView?.collectionViewLayout.springinessEnabled = false 

    automaticallyScrollsToMostRecentMessage = true 

    // self.collectionView?.reloadData() 
    self.collectionView?.layoutIfNeeded() 




    self.isLoading = false 

    self.loadMessages() 


} 


override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    collectionView!.collectionViewLayout.springinessEnabled = false 


timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ChatMessagesViewController.loadMessages), userInfo: nil, repeats: true) 


} 

func addMessage(_ id: String, text: String) { 
    print("add message: \(text)") 



    let message = JSQMessage(senderId: id, displayName: "Me", text: text) 


    messages.append(message) 



} 

func loadMessages() { 

// self.messages = [JSQMessage]() 

    // self.messages.removeAll() 

    if self.isLoading == false { 

     isLoading = true 

     self.getChatHistory(mYURL) 


     finishReceivingMessage() 


    } 

} 

FUNC의 getChatHistory (_ URL : 문자열) {

(: sentBy, SentTo : SentTo, 메시지 : 메시지, IsType : IsType, SentOn : mesSentOn SentBy)

          self.chatHist.append(add) 

              self.from = SentTo 
              self.to = sentBy 

              var message:String="" 

              if let range = Message.range(of: ";") { 

              message = Message.substring(from: range.upperBound) 
              } 

              self.addMessage(IsType, text: message) 


             } 
            } 
           } 
          } 

         } 

        self.do_collectionView_refresh() 

        } 



       } 



      } 
      catch { 

       print("Error with Json: \(error)") 
      } 

     } 
    } 


    isLoading = false 

    task.resume() 



} 

FUNC의 do_collectionView_refresh() {

//
messages.removeAll() 
    // messages.removeAll(keepingCapacity: true) 

    let requestURL: URL = URL(string: url)! 
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL) 
    let session = URLSession.shared 
    let task = session.dataTask(with: urlRequest as URLRequest) {data,response,error in 

     let httpResponse = response as! HTTPURLResponse 
     let statusCode = httpResponse.statusCode 

     if (statusCode == 200) { 
      print("everything is fine, file downloaded successfully.") 

      print(response!) 


      do{ 



       let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) 

       if let items = json as? [[String: AnyObject]] { 



        for item in items { 

         if let sentBy = item["SentBy"] as? String { 

          if let SentTo = item["SentTo"] as? String { 

           if let Message = item["Msg"] as? String { 

            if let IsType = item["IsType"] as? String { 

             if let mesSentOn = item["MsgSenton"] as? String //Date { 

             { 

는 = chatHistory을 추가 할 수

DispatchQueue.main.async { 

     self.collectionView?.reloadData() 

    } 
} 


override func senderId() -> String { 
    return userType 
} 

override func senderDisplayName() -> String { 
    return "Me" 
} 

override func collectionView(_ collectionView: UICollectionView, 
          numberOfItemsInSection section: Int) -> Int { 

    if messages.count > 0 { 

     return messages.count 
    } 
    else { 

     return 0 
    } 


    // return messages.count 
} 


override func collectionView(_ collectionView: JSQMessagesCollectionView, messageDataForItemAt indexPath: IndexPath) -> JSQMessageData { 

    //app Crashes here : fatal error: Index out of range 
     return messages[indexPath.item] 


} 


override func collectionView(_ collectionView: JSQMessagesCollectionView, messageBubbleImageDataForItemAt indexPath: IndexPath) -> JSQMessageBubbleImageDataSource { 

// return messages[indexPath.item].senderId == self.senderId() ? outgoingBubble : incomingBubble 

    let message = messages[indexPath.item] 

    // let message = chatHist[indexPath.item] 
    // 1 
    if message.senderId == userType { // 

     return outgoingBubbleImageView 
    } else { // 3 
     return incomingBubbleImageView 
    } 

} 

오류가 발생했습니다. 제발 도와주세요.

답변

0

이 차이가 있는지 알려주세요 : Alex7 @ 답장을

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return messages.count 

} 

override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { 

    let data = self.messages[indexPath.row] 
    return data 

} 

override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { 

    let data = messages[indexPath.row] 
    switch(data.senderId) { 
    case self.senderId: 
     return self.outgoingBubbleImageView 
    default: 
     return self.incomingBubbleImageView 
    } 
} 
+0

감사합니다. 나는 위의 솔루션을 시도했지만 그것은 나를 위해 작동하지 않았다. –