2012-04-16 1 views
0

私のアプリでは、実際にはiTunesの曲とプレビューを再生する音楽プレーヤーがあります。 しかし、AVAudioプレーヤーは、ファイルを再生するためにローカルファイルに書き込まれる必要があります。だから私は自分の再生ボタンをクリックしてから2〜3秒かかるので、私はボタンにUIActivityIndi​​catorビューを表示して、ユーザーがその読み込みを知っているようにしたいと思っていました。次のアクションを実行するためのアクションが完了するまでどのように停止するのですか?

私は他のビュー読み込みのためにそれを行う方法を知っていますが、ここではすべてが1つのメソッド内で起こっているので、これを行う方法は分かりません。ここで

は私のコードです:

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

"そのすべての単一メソッドの内部で起こって"、それはすぐそこに問題です。責任を分け合わせると柔軟性が増します。 1つの方法が多すぎるタスクを担当します。 – aryaxt

+0

でも、私はperformSelectorOnMainThread:untilDoneをやるだけでいいですか? – Ashutosh

+0

あなたは以下の答えのような何かをしなければならないでしょう。 gui、この場合は待機インジケータは、関数が完了するまで更新されません。別のスレッド上で別の関数で作業をしなければなりません。 – clarky

答えて

2

performSelectorInBackgroundを呼び出すことにより、バックグラウンドで実行するには、ブロッキングタスクを持っています。タスクが完了したときに通知を受けるには、ブロックを渡すか、デリゲートを使用します。

FileStorage.h

@protocol FileStorageDelegate <NSObject> 
- (void)fileStorageDidWriteToFile; 
@end 

@interface FileStorage 

@property (nonatomic, assign) id <FileStorageDelegate> delegate; 

@end 

FileStorage.m

関連する問題