如何使用gksession发送和接收数据?

时间:2011-03-14 09:30:28

标签: iphone bluetooth chat gksession

您好 我使用gksession.code发送数据如下。这里发送数据工作正常 并给出发送数据的消息。但我无法接收其他数据 当我调试代码时,它不会调用并进入方法 接收数据。有人对此有任何想法吗?这里有什么问题,或者我怎么办? 解决问题?

- (void)viewDidLoad {
    [super viewDidLoad];
    gs=[manager getgkSession];
    //[cs retain]
    self.title = [manager displayNameForPeer:manager.currentConfPeerID];
    NSLog(@"name of mangager is %@",self.title);

}


-(IBAction) btnSend:(id) sender
{
    //---convert an NSString object to NSData---
    NSData* data;
    NSError *error=nil;
    NSString *str = [NSString stringWithString:txtMessage.text];
    data = [str dataUsingEncoding: NSASCIIStringEncoding];     
    if (gs) 

    {
        [self.gs sendDataToAllPeers:data 
                       withDataMode:GKSendDataReliable 
                              error:&error];    
            if (!error) 
        {
            NSLog(@"Did send data");
        } 
        else 
        {
            NSLog(@"Send data failed: %@", [error localizedDescription]);
        }   
    }        
}


    - (void) receiveData:(NSData *)data 
                fromPeer:(NSString *)peer 
               inSession:(GKSession *)session 
                 context:(void *)context {

        //---convert the NSData to NSString---
        NSString* str;
        str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];    
        NSLog(@"data received is %@",str);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data received" 
                                                        message:str 
                                                       delegate:self 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        NSLog(@"receive data");
        [alert show];
        [alert release];    
    }

2 个答案:

答案 0 :(得分:2)

您是否为接收方拨打了setDataReceiveHandler:withContext: GK会话? 如果在开始发送数据之前没有这样做。

答案 1 :(得分:2)

确保在头文件中实现此目的:GKPeerPickerControllerDelegate