I'm currently working with the Multipeer Connectivity Framework in XCode for an iPad App.
I want to send messages with the framework (NSStrings, Booleans & NSArrays) and Strings are working fine, but I need some sort of type-check to convert the NSData object into a String, Array, etc.
This is what my didReceiveData methode looks like:
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSMutableArray *recievedArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if ([message isEqualToString:@"PeerIsConnected"]) {
NSLog(@"Peer sended: Connected!");
self.connectionIsOn = TRUE;
dispatch_async(dispatch_get_main_queue(),^{
[self changeConnectionButton:TRUE];
});
NSLog(@"Connection is on (data received) : %@", (self.connectionIsOn) ? @"YES" : @"NO");
}
if ([message isEqualToString:@"Disconnect"]) {
NSLog(@"Peer sended: Disconnect!");
self.connectionIsOn = FALSE;
dispatch_async(dispatch_get_main_queue(),^{
[self changeConnectionButton:FALSE];
});
}
if ([message isEqualToString:@"GoWasClicked"]) {
self.muliplayergameIsOn = TRUE;
self.myTurn = TRUE;
self.startDate = [NSDate date];
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
I need some if case so I can cast the NSData object into a NSString OR NSArray OR etc.
How can I solve this problem?
Thanks in advance!
EDIT: This is how the Array is sended:
- (void) sendArray:(NSMutableArray *) arrayToSend{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayToSend];
NSError *error;
[self.mySession sendData:data toPeers:[self.mySession connectedPeers] withMode:MCSessionSendDataUnreliable error:&error];
}
You could use NSKeyedArchiver
for all kinds of objects that you send
(string, array, ...). Then you can check on the receiving side with
id receivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if ([receivedObject isKindOfClass:[NSArray class]]) {
NSArray *receivedArray = receivedObject;
// handle array ...
} else if ([receivedObject isKindOfClass:[NSString class]]) {
NSString *receivedString = receivedObject;
// handle string ...
}