Question

I am trying to implement the multipeer connectivity framework into my application.

I have successfully done this. What I want the user to be able to do is select something like a picture from the camera roll and pass it over to another connected device. I'm doing it with other things though, not just UIImage, (e.g. NSString, NSObject...)

Ideally, what I want to be able to do is to be able to use it and receive it using one of the two methods:

- (void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID;

OR

- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {

What I want, however, is a standardised way (for any object type) to pass it over to another device using multipeer connectivity.

My only thought was to convert each object into NSData and then pass it over, however, this does not work on the receiving end. My test is:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:self.myImage];
NSLog(@"%@", myData);

Then I have no idea how to convert it back. Is it something to do with NSCoding?? Any ideas would be much appreciated! :) Thank you!!

Was it helpful?

Solution

Sounds like you have the right idea, you just need to use NSKeyedUnarchiver when the data is received.

- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {

    id myObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

From there you can determine what kind of object you actually received:

if ([myObject isKindOfClass:[SomeClass class]]){

   //Handle
}

This will work for any class, as long as it conforms to the NSCoding protocol. Take a look at: Encoding and Decoding Objects

OTHER TIPS

What I would suggest is implementing a protocol to transfer NSData objects between devices. Have a standardised packet that you send between devices. Such as

type | length | data....

The type and length should be integers so when they get to the other side you know exactly how big they are. The length will then tell you how long your actual packet is.

A simple example

// method received "(id) data" which can be UIImage, NSString, NSDictionary, NSArray

// 1 -> Image
// 2 -> JSON
uint32_t type;

if ([data isKindOfClass:[UIImage class]]) {
   data = UIImageJPEGRepresentation((UIImage *)data, 1.0);
   type = 0;
} else {
   data = [data JSONData];
   type = 1;
}

uint32_t length = [data length];

NSMutableData *packet = [NSMutableData dataWithCapacity:length + (INT_32_LENGTH * 2)];
[packet appendBytes:&type length:INT_32_LENGTH];
[packet appendBytes:&length length:INT_32_LENGTH];
[packet appendData:data];

Then on the other end you just read the length of the packet check the type and convert back to the correct object type. For Images send as binary packet and for anything else send as JSON.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top