Search code examples
iosswiftnsdatamultipeer-connectivity

How to combine these several different value type to NSData?


I need to use MultipeerConnectivity to send images and some set of arrays of strings to another device. On the receiver side, the API is func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID), it only receives NSData data. But I need to send something like this:

struct data{
var imageData:NSData?
var location:[String:String]?
var information:[String]?
var sliderInfo:[String]?
var questionsAndAnswer:[String:String]?
var secrets: String?
var tempts: Int?

}

There are many different value types inside the dataStructure, but how do I convert this custom data structure to NSData and then decode that on the receiver side? I'm using Swift for this project.


Solution

  • I use another way to solve this problem: On the sender side, send the Dictionary:[String:[String]], encode that, and decode that on the receiver side. For NSData, I send that again. Seprate it from the other data.

            let imageData = UIImageJPEGRepresentation(self.detailImage!, 1.0)
    
            let msg = ["clickHidenInfo":[clickHidenInfo],"swipeInfo":upDownLeftRight,"sliderInfo":slideHiddenInforation,"locationInfo":["x1,y1,info","x2,y2,info"],"qa":["what's your name","Jerry"],"hints":["hints I provide"],"tempts":["tempts you can use"]]
    
    
    
    //sender:
            let msgData = NSKeyedArchiver.archivedDataWithRootObject(msg)
    
            do
            {
                try self.session?.sendData(imageData!, toPeers: (self.session?.connectedPeers)!, withMode: .Unreliable)
                print("succee")
            }
            catch{
                print("failure")
            }
    
            do
            {
                try self.session?.sendData(msgData, toPeers: (self.session?.connectedPeers)!, withMode: .Unreliable)
                print("succee")
            }
            catch{
                print("failure")
            }
    //receiver side
    dispatch_async(dispatch_get_main_queue()){
    
    
            let dict = NSKeyedUnarchiver.unarchiveObjectWithData(data)
            if dict == nil
            {
                self.guessImage.image = UIImage(data: data)
                self.guessImage.reloadInputViews()
            }
            else
            {
                let result = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Dictionary<String,[String]>
                let a = result!["swipeInfo"]
                print("\(a![0])")
            }
    
    
        }