在我的应用程序中,我有一个音乐播放器,它实际上是来自 iTunes 的歌曲并播放预览。但是由于 AVAudio 播放器需要将文件写入本地文件才能播放。所以有时在我点击我的播放按钮后需要 2-3 秒,所以我想在我的按钮上显示一个 UIActivityIndicator 视图,以便用户知道它的加载。
我知道如何为其他视图加载执行此操作,但在这里它一个接一个地发生在一个方法中,所以不知道如何执行此操作。
这是我的代码:
wait = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
UIView * temp = (UIView *)sender;
[temp addSubview:wait];
[wait startAnimating];
NSError * error;
int tag = [sender tag]-100;
previousTag = sender;
active = sender;
UIButton * button = (UIButton *)sender;
[UIView transitionWithView:button
duration:0.5
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
[button setBackgroundImage:pauseButtonImage.image forState:UIControlStateNormal];
}
completion:NULL];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
[songsResults selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
NSString * floatPath = [NSString stringWithFormat:@"preview%d",tag];
NSString *uniquePath = [TMP stringByAppendingPathComponent: floatPath];
if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
{
[wait stopAnimating];
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:uniquePath] error:&error];
}
else {
NSArray * temp = [dataToDisplay objectAtIndex:tag];
NSString * urlString = [temp objectAtIndex:3];
NSURL *url = [NSURL URLWithString:urlString];
NSData *soundData = [NSData dataWithContentsOfURL:url];
[soundData writeToFile:uniquePath atomically:YES];
[wait stopAnimating];
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:uniquePath] error:&error];
}
float duration = [audioPlayer duration];
timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(stopPreview:) userInfo:nil repeats:NO];
[audioPlayer play];
isPlaying = YES;
}