我目前正在使用XCode中的Multipeer Connectivity Framework获取iPad应用程序。
我想用框架发送消息(NSStrings,Booleans和NSArrays)并且Strings工作正常,但是我需要某种类型检查来将NSData对象转换为String,Array等。
这就是我的didReceiveData方法:
- (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];
}
我需要一些if case,所以我可以将NSData对象转换为NSString或NSArray OR等。
我该如何解决这个问题?
提前致谢!
编辑:这就是数组的发送方式:
- (void) sendArray:(NSMutableArray *) arrayToSend{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayToSend];
NSError *error;
[self.mySession sendData:data toPeers:[self.mySession connectedPeers] withMode:MCSessionSendDataUnreliable error:&error];
}
答案 0 :(得分:1)
您可以将NSKeyedArchiver
用于您发送的各种对象
(字符串,数组,...)。然后,您可以使用
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 ...
}
答案 1 :(得分:1)
//Added one more condition here...
id receivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if ([receivedObject isKindOfClass:[NSArray class]]) {
NSArray *receivedArray = receivedObject;
// handle array ...
}
else if ([receivedObject isKindOfClass:[NSDictionary class]]) {
NSString *receivedString = receivedObject;
// handle dictionary ...
}
else if ([receivedObject isKindOfClass:[NSString class]]) {
NSString *receivedString = receivedObject;
// handle string ...
}