3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

n秒後に1回実行、もしくは実行をキャンセル

Last updated at Posted at 2016-12-18

具体的にはこんなことをしたい時の処理

iosで長いローディングが始まってからn秒後に広告を出す
もしくはn秒以内にローディングがキャンセルされたら広告を出さない

isCancelフラグをもってdispatch_afterで分岐させようとしたがダメだった

うまくいいったソースは以下の通り

実装(Objective-C)

static dispatch_source_t _timer;
static int N = 5;

//N秒後に1度だけ実行
-(void)hoge{
   //タイマーを生成
  _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
  //イベントを設定
  dispatch_source_set_event_handler(_timer, ^{
    /********************
    N秒後に1度だけやりたいことをここに書く
    *******************/
    //一度実行したらキャンセル
    dispatch_source_cancel(_timer);
  });
  //開始時間を設定
  dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, N * NSEC_PER_SEC);
  //タイマーをセット
  dispatch_source_set_timer(_timer, start, 100 * N * NSEC_PER_SEC, 0);
  //タイマーを実行
  dispatch_resume(_timer);
}

//N秒以内にこのメソッドを呼べば実行しない
-(void)cancelTimer{
  if(_timer) dispatch_source_cancel(_timer);
}

さいごに

スニペットとかありそうな気がするけど見つからず...
もっと良い方法ありそう
あとそろそろswift覚えよ

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?