以 20 秒延迟调用多点方法中的代码

Posted

技术标签:

【中文标题】以 20 秒延迟调用多点方法中的代码【英文标题】:Code in multipeer method called with 20s delay 【发布时间】:2013-10-02 20:18:55 【问题描述】:

我正在使用多点连接,这是其中一种方法:

-(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】:

会话委托的方法可能在后台线程上被调用。 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];

【讨论】:

+1。来自 MCSession 文档,“重要提示:委托调用发生在私有操作队列上。如果您的应用需要对特定运行循环或操作队列执行操作,则其委托方法应显式调度或安排该工作。”

以上是关于以 20 秒延迟调用多点方法中的代码的主要内容,如果未能解决你的问题,请参考以下文章

为啥不以指定的延迟进行 ajax 调用

Clipboard.SetText 调用延迟 5 秒

unity3d中的怎么实现update的延迟调用

如何在两个计时器之间创建延迟?

调用 record() 时 AVAudioRecorder 长时间延迟

延迟方法调用[重复]