以20s延迟调用的多重方法中的代码

时间:2013-10-02 20:18:55

标签: ios uikit multipeer-connectivity

我正在使用多重连接,这是方法之一:

-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress

{
NSLog(@"RECEIVING... %@ from peer: %@", progress, peerID);

UIProgressView *progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
progressBar.frame = CGRectMake(0, 200, 100, 20);
progressBar.progress = 0.5;
UIButton* btn = [BluetoothDeviceDictionary objectForKey:peerID];
[self.view addSubview:progressBar];

UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"Alert View Title" message:@"Alert View Text" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alertView show];
}

由于某些非常严重的原因,当调用此方法时,我知道由于NSLog的响应而调用它,其余代码不会被执行。 NSLog出现后,警报显示20秒(或多或少),并且进度视图永远不会出现。我不明白为什么。对于多重连接框架中的大多数方法都会发生这种情况。这怎么可能?

编辑:实际上会显示进度视图,但在调用方法后会出现很多

1 个答案:

答案 0 :(得分:5)

可能在后台线程上调用会话委托的方法。 UIKit调用只应在主线程上进行,因此您可能需要将与UIKit交互的代码移动到另一个方法,如下所示:

- (void) updateUI {
    UIProgressView *progressBar = [[UIProgressView alloc];
    initWithProgressViewStyle:UIProgressViewStyleBar];
    progressBar.frame = CGRectMake(0, 200, 100, 20);
    progressBar.progress = 0.5;
    UIButton* btn = [BluetoothDeviceDictionary objectForKey:peerID];
    [self.view addSubview:progressBar];

    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"Alert View Title" message:@"Alert View Text" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];
}

然后使用:

调用它
-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress
{
    NSLog(@"RECEIVING... %@ from peer: %@", progress, peerID);
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
}