Search code examples
xcodeswiftparse-platformsinch

Could not cast value of type SINMessage to ChatMessage (Swift)


Currently trying to bridge the Sinch SDK into my Swift app and I'm running across the following error:

"Could not cast value of type 'SINMessageRebRTCImpl'" to 'ChatMessage'"

1) The type SINMessageRebTyCImpl is created in the following function located in the AppDelegate.swift file:

 func messageSent(message: SINMessage, recipientId: String) {
    self.saveMessagesOnParse(message)
**NSNotificationCenter.defaultCenter().postNotificationName(SINCH_MESSAGE_SENT, object: self, userInfo: ["message": message])** }

2) SINMessageRebTyCImpl is then passed to the following function located in one of my viewcontrollers

func messageDelievered(notification: NSNotification){
let chatMessage: ChatMessage = (notification.userInfo["message"] as! ChatMessage)
self.messageArray.append(chatMessage)
}

3) The code then crashes at the second line of the above snippet.

let chatMessage: ChatMessage = (notification.userInfo["message"] as! ChatMessage)

For more information, here is the code for the swift class "ChatMessage" that I am trying to cast too.

Import UIKit
Import Foundation

class ChatMessage: NSObject, SINMessage {
    var messageId: String
    var recipientIds: [AnyObject]
    var senderId: String
    var text: String
    var headers: [NSObject : AnyObject]
    var timestamp: NSDate
}

(Note, "Import Sinch" does not need to be in the above listed "ChatMessage" class because I have it in the Bridging-Header)

So, what am I missing/doing wrong?


Solution

  • Okay...

    So after days of testing workarounds, I found my solution. The issue seemed to be that, like bolnad suggested, the "SIN" type was not fitting the requirements of the "ChatMessage" class.

    So, rather than trying to pass the entire array through a NSNotification variable, I broke it out as follows and set them as NSDefaults

    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()    
        chatMessage.senderId = prefs.valueForKey("SENDERID") as! String
        chatMessage.text = prefs.valueForKey("TEXT") as! String
        chatMessage.messageId = prefs.valueForKey("MESSAGEID") as! String
        chatMessage.timestamp = prefs.valueForKey("TIMESTAMP") as! NSDate
        chatMessage.recipientIds = prefs.valueForKey("RECIPIENTID")  as! [AnyObject]!
        self.messageArray.append(chatMessage)
        self.historicalMessagesTableView.reloadData()
        self.scrollTableToBottom()
    

    In doing so, I was able to satisfy the "ChatMessage" class without issue!

    Thanks to everyone who assisted.