首页 > 解决方案 > NSData 结果导致 NSTimer 延迟

问题描述

我有一个 NSTimer 应该在 10 秒后触发它的选择器。但是由于 NSData 结果的延迟,计时器也被延迟,并且在执行 NSData 操作后触发其选择器。

        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0
                                         target:self
                                       selector:@selector(fireTimer)
                                       userInfo:nil
                                        repeats:NO];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:decryptedPath]];
        _audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];

在上面的代码中,Timer 等待 NSData 结果然后触发它的选择器。

标签: iosobjective-cxcodenstimernsdata

解决方案


这是因为dataWithContentsOfURL:阻塞了主队列(这是计时器触发的地方)。你不应该那样做。您需要先使用 NSURLSession 下载它,一旦完成,然后将数据传递给 AVAudioPlayer。AVAudioPlayer 不是为流媒体设计的。


推荐阅读