线程1:EXC_BAD_INSTRUCTION在尝试编写消息JSQMessagesViewController时

时间:2016-09-10 08:59:14

标签: ios swift xcode jsqmessagesviewcontroller

See this pic for error

当我尝试写一条消息时,它会崩溃。我似乎无法在这里找到错误。我得到一个Thread 1: EXC_BAD_INSTRUCTION (code=EXC)_1386_INVOP, subcode=0x0.我试图找到我的字符串上的问题。对不起,我只是新的xcode

完整代码位于下方

import UIKit
import JSQMessagesViewController
import MobileCoreServices
import AVKit
import FirebaseDatabase

class ChatViewController: JSQMessagesViewController {
    var messages = [JSQMessage]()

    var messageRef = FIRDatabase.database().reference().child("messages")


    override func viewDidLoad() {
        super.viewDidLoad()

        self.senderId = "1"
        self.senderDisplayName = "Ej"
        //messageRef.childByAutoId().setValue("first message")
        //messageRef.childByAutoId().setValue("2nd")
//        messageRef.observeEventType(FIRDataEventType.Value) { (snapshot: FIRDataSnapshot) in
//            if let dick = snapshot.value as? NSDictionary {
//                print(dick)
//            }
//        }
        observeMessages()


    }

    func observeMessages(){

        messageRef.observeEventType(.ChildAdded, withBlock: { snapshot in
            //print(snapshot.value)

                if let dick = snapshot.value as? [String: AnyObject]{
                //let Mediatype = dick["Mediatype"] as! String
                let senderId = dick["senderId"] as! String
                let senderName = dick["senderName"] as! String
                let text = dick["text"] as! String  
                self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
                self.collectionView.reloadData()
            }
        })
    }

    //Send Btn
    override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {

    //Messages
        //messages.append(JSQMessage(senderId: senderId, displayName: senderDisplayName, text: text))
       //self.collectionView.reloadData()
//        print(messages)

        let newMessage = messageRef.childByAutoId()
        let messageData = ["text": text, "senderId": senderId, "senderName": senderDisplayName, "Mediatype": "TEXT"]
        newMessage.setValue(messageData)



    }
    //File btn
    override func didPressAccessoryButton(sender: UIButton!) {
        // ALERT WHEN PRESSED ACCESSORY
        let sheet = UIAlertController(title: "Media Messages", message: "Select A Media", preferredStyle: UIAlertControllerStyle.ActionSheet)
        let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (alert:UIAlertAction) in

        }

        let photoLibrary = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.Default) { (alert: UIAlertAction) in
            self.getMediaFrom(kUTTypeImage)
        }

        let videoLibrary = UIAlertAction(title: "Video Library", style: UIAlertActionStyle.Default) { (alert: UIAlertAction) in
            self.getMediaFrom(kUTTypeMovie)


        }

        sheet.addAction(photoLibrary)
        sheet.addAction(videoLibrary)
        sheet.addAction(cancel)
        self.presentViewController(sheet, animated: true, completion: nil)



        //let imagePicker = UIImagePickerController()
        //imagePicker.delegate = self
        //self.presentViewController(imagePicker, animated: true, completion: nil)


        }

    func getMediaFrom(type: CFString) {
        print(type)
        let mediaPicker = UIImagePickerController()
        mediaPicker.delegate = self
        mediaPicker.mediaTypes = [type as String]
        self.presentViewController(mediaPicker, animated: true, completion: nil)



    }


    override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
        return messages[indexPath.item]
    }

    //BUBBLE CHAT
    override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
        let bubbleFactory = JSQMessagesBubbleImageFactory()
        return  bubbleFactory.outgoingMessagesBubbleImageWithColor(.lightGrayColor())
    }

    override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
        return nil
    }





    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("number of items  \(messages.count)")
        return messages.count
    }


    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell

        return cell
    }


   override func collectionView(collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {

        print("didTappedMessageBubbleAtIndexPath \(indexPath.item)")
        let message = messages[indexPath.item]
    if message.isMediaMessage {
        if let mediaitem = message.media as? JSQVideoMediaItem{
            let player = AVPlayer(URL: mediaitem.fileURL)
            let playerView = AVPlayerViewController()
            playerView.player = player

            self.presentViewController(playerView, animated: true, completion: nil)
        }

    }

    }



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

    @IBAction func LogOutTapped(sender: AnyObject) {
       print ("User Logged Out")
        //Goes on to Chat View




        //Main Stroryboard Interface
        _ = UIStoryboard(name: "Main", bundle: nil)



        //From MainStoryboard instatiate a navigation controller

        let LoginVC = storyboard?.instantiateViewControllerWithIdentifier("LoginVC") as! LogInViewController



        //Get app delegate

        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate




        //Navigation Controller as root view controller

        appDelegate.window?.rootViewController = LoginVC


    }


}


extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print("finish picking")
        print(info)
        if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage {
            let photo = JSQPhotoMediaItem(image: picture)
            messages.append(JSQMessage(senderId: senderId, displayName: senderDisplayName, media: photo))
        }else if let video = info[UIImagePickerControllerMediaURL] as? NSURL{
            let videoitem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
            messages.append(JSQMessage(senderId: senderId, displayName: senderDisplayName, media: videoitem))
        }

        self.dismissViewControllerAnimated(true, completion: nil)
        collectionView.reloadData()
    }



}

2 个答案:

答案 0 :(得分:0)

错误告诉您dick["text"]实际上是意外的零。

尝试这样做:

let text = dick["text"] ?? ""

应该用空字符串替换nil。

答案 1 :(得分:0)

我建议您查看guard声明。这是一个声明,可以让您检查可选"?"的值。如果它是零,那么它处理这种情况,因为如果你没有消息的所有必需信息。如果消息没有文本,您不希望在对话中显示它。它与您已经拥有的if let语句非常相似,但它使您无需在if let内嵌套if let  所以我建议你把逻辑变成更像这样的东西。

messageRef.observeEventType(.ChildAdded, withBlock: { snapshot in
   guard let dick = snapshot.value as? [String: AnyObject] else { return } 
     // This will return if the snapshot cannot be mapped to the dictionary format [String: AnyObject]    
   guard let senderId = dick["senderId"] as! String, senderName = dick["senderName"] as! String, text = dick["text"] as! String else { return } 
     // This will return if the "dick" object does not contain all the elements necessary to create a JSQMessage
     // Otherwise we want to add it to our messages list   
            self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
            self.collectionView.reloadData()
        }

现在你也想看看这个逻辑。您的dick对象看起来更像是一般消息对象。不管"迪克"曾经是发送消息的人。除非你引用" dick"特别是通过firebase的路径。从它的外观来看var messageRef = FIRDatabase.database().reference().child("messages")我认为它就是你在后端存储所有消息的地方。 我可能没有完全理解这里的目的,但我希望有所帮助。如果您有其他问题,请与我们联系。