从后台获取一个积累的时间,在视图上显示并且要实时更新

2018-04-26  本文已影响0人  芭里克婷

1.看到这个肯定会想到加一个定时器不断请求,然后不断刷刷新视图;其次就会想到需要在次线程加定时器+请求,回到主线程刷新视图。

2.下面用了一个__block 类型的count,可以在线程块里改变它的数值;我想要定时器在第一次和第二次每隔0.05秒请求一次数据(因为可能创建视图了但数据还没回来,所以需要快点请求第二次刷新下),第一次创建视图,在后面就隔60秒请求并且更新一下视图。

-(void)addTimeupdateThread{

    int  __block count =0;

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];

    // 可以用该语句查看当前线程

    NSLog(@"当前线程--%@", [NSThreadcurrentThread]);

    // 此处需要写一个异步任务,是因为需要开辟一个新的线程去反复执行你的代码块,否则会阻塞主线程

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

        while(TRUE) {

  // 这里写你要反复处理的代码,如网络请求

             count++;

             if(count==1||count==2) {

                [NSThreadsleepForTimeInterval:0.05];

                 [self  getdriverOnTime];

                 NSLog(@"第一次请求数据");

            }else{

                // 每隔5秒执行一次(当前线程阻塞5秒)

                [NSThreadsleepForTimeInterval:60];

                [self  getdriverOnTime];

         }

          [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

  dispatch_async(dispatch_get_main_queue(), ^{

                if(jobView==nil) {

                    [self addJobingView];

                    NSLog(@"创建了视图");

                    }elseif(jobView!=nil&&self.ondutytime!=nil){

                    jobView.numberHour.text= [NSStringstringWithFormat:@"%ld",[jobView.dic[@"Result"]integerValue]/60] ;

                    jobView.numberMin.text=[NSStringstringWithFormat:@"%ld",[jobView.dic[@"Result"]integerValue]%60] ;

//                    jobView.numberMin.text = [NSString stringWithFormat:@"%d",count];

                    [[UIApplication sharedApplication] cancelAllLocalNotifications];

                    NSLog(@"刷新了一次");

                }

            });

        };

    });

}

-(void)getdriverOnTime{

//你自己的数据请求

}

- (void)addJobingView{

//声明你需要的视图并且赋值。

}

上一篇 下一篇

猜你喜欢

热点阅读