0
在我的應用程序中,我有一個音樂播放器,實際上是從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;
}
「所有的單一方法中發生了」,這就是問題就在這裏。分開責任,你會獲得更多的靈活性。你的單一方法負責太多的任務。 – aryaxt 2012-04-16 00:40:02
好吧,但仍然應該只是做performSelectorOnMainThread:untilDone? – Ashutosh 2012-04-16 00:42:36
你必須做下面的答案。在這種情況下,等待指示器gui不會更新,直到函數完成。您必須在單獨的線程上的單獨函數中完成這項工作。 – clarky 2012-04-16 04:01:49