在我的应用程序中,我有一个音乐播放器,实际上是来自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;
}
答案 0 :(得分:2)
通过调用performSelectorInBackground
让阻止任务在后台运行。并且为了在任务完成时得到通知,要么传递一个块,要么使用一个代表。
FileStorage.h
@protocol FileStorageDelegate <NSObject>
- (void)fileStorageDidWriteToFile;
@end
@interface FileStorage
@property (nonatomic, assign) id <FileStorageDelegate> delegate;
@end
FileStorage.m
@implementation FileStorage
@synthesize delegate = _delegate;
- (void)storeFile:(NSData *)data
{
[self performSelectorInBackground:@selector(storeFileInBackground:) withObject:data];
}
- (void)storeFileInBackground:(NSData *)data
{
// perfofm blocking task
// Call delegate and pass some parameters if needed
[self.delegate fileStorageDidWriteToFile];
}
@end