iOS轮询请求并在图表中动态显示

最近接到一个需求,需要iOS设备实时获取服务器的数据,并动态显示在图表中。

主要工作有以下几点:1、写一个轮询,每隔一段时间就从服务器获取数据;2、根据获取到的数据显示在图表中。

1、轮询操作:

轮询的方法很多,比如通过NSthread起个线程,并在子线程中循环请求服务数据,通过GCD的定时器也可以实现,本文采用的是通过RunLoop的形式,RunLoop的优势大家可以百度下。不过这些都不是最优方法,最好的是通过websocket。

话不多说,直接上代码吧。

runLoop模块:

新建图表显示的控制器类:DeviceChartViewController

-(void)myRunloop

{

[NSThread detachNewThreadSelector:@selector(newThreadFun) toTarget:self withObject:nil];

}

-(void)newThreadFun

{

@autoreleasepool {

end =NO;

NSRunLoop * myRunLoop =[NSRunLoop currentRunLoop];

CFRunLoopObserverContext context = {0,CFBridgingRetain(self),NULL,NULL,NULL};

CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &myRunLoopObserver, &context);

if (observer) {

CFRunLoopRef cfRunloop = [myRunLoop getCFRunLoop];

CFRunLoopAddObserver(cfRunloop, observer, kCFRunLoopDefaultMode);

}

[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerprocess) userInfo:nil repeats:YES];

while (!end) {

[myRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];

}

}

}

-(void)timerprocess{

ESPCNetworkDeviceDetailRequest *request = [[MyRequest alloc] init];

[self request:request];

}

void myRunLoopObserver(CFRunLoopObserverRef observer,CFRunLoopActivity activity,void* info)

{

switch (activity) {

case kCFRunLoopEntry:

NSLog(@"run loop entry");

break;

case kCFRunLoopBeforeTimers:

NSLog(@"run loop before times");

break;

case kCFRunLoopBeforeSources:

NSLog(@"run loop before sources");

break;

case kCFRunLoopBeforeWaiting:

NSLog(@"run loop before waiting");

break;

case kCFRunLoopAfterWaiting:

NSLog(@"run loop after waiting");

break;

case kCFRunLoopExit:

NSLog(@"run loop exit");

break;

default:

break;

}

}

请求后的结果处理:

- (void)NetworkDidFinishLoad:(NetworkProvider *)provider

{

if (provider == myProvider) {

_dRep = myProvider.torResponse;

if ([_dRep.code isEqualToString:@"1"]) {

NSDictionary *dict = _dRep.detailInfoDict;

NSNumber * statusvalue;

statusvalue = [dict objectForKey:@"statusValue"];

[self.lineChart addPoint:statusvalue.floatValue]; //图表处理函数

}

}

}

- (void)espcNetwork:(TORBaseNetworkProvider *)provider didFailLoadWithError:(NSError *)error

{

if (provider == _deviceDetailProvider) {

[self hideHUD];

_dRep = (ESPCNetworkDeviceDetailResponse*)_deviceDetailProvider.torResponse;

NSString*msg = @"没有获取到数据,请稍后重试!";

if (_dRep&&_dRep.msg) {

msg = _dRep.msg;

}

}

}

2、图表处理

新建一个UIView的类DSGraphChart

//

//  DSGraphChart.h

//

//  Created by icarus on 15/11/27.

//  Copyright © 2015年 icarus. All rights reserved.

//

#import

@interface DSGraphChart : UIView{

UIColor *strokeColor;

UIColor *zeroLinestrokeColor;

UIColor * unitLinestrokeColor;

int strokeLineWidth;

int zeroLineWidth;

int unitLineWidth;

NSMutableArray * pointsArray;

double ymax;

double ymin;

double defaultValue;

int ValueNum;

int unitNum;

NSInteger chartHeight;

NSInteger chartWidth;

int topOffset;

}

-(void)addPoint:(float)pointvalue;

-(void)setPoints:(float)value;

-(void)setDefaultVaule:(float)value;

@end

//

//  DSGraphChart.m

//  Created by icarus on 15/11/27.

//  Copyright © 2015年 icarus. All rights reserved.

//

#import "DSGraphChart.h"

@implementation DSGraphChart

-(id)initWithFrame:(CGRect)frame

{

if (self=[super initWithFrame:frame]) {

ymax =100.0;

ymin =0.0;

[self setBackgroundColor:[UIColor whiteColor]];

strokeLineWidth = 2 ;

zeroLineWidth = unitLineWidth =1;

strokeColor = [UIColor greenColor];

zeroLinestrokeColor = [UIColor blackColor];

unitLinestrokeColor = [UIColor grayColor];

defaultValue =50;

ValueNum =10;

unitNum = 5;

pointsArray =[[NSMutableArray alloc] init];

for (int i=0; i

[pointsArray addObject:[NSNumber numberWithFloat:defaultValue]];

}

topOffset =8;

chartHeight = self.frame.size.height-topOffset;

for (int i=0; i<=unitNum; i++) {

NSInteger labelHeght =10;

UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height-chartHeight/unitNum*i-topOffset/2-labelHeght/2, self.frame.size.width/ValueNum, labelHeght)];

[label setText:[NSString stringWithFormat:@"%1.1f",(ymax-ymin)/unitNum*i]];

[label setTextAlignment:NSTextAlignmentCenter];

[label setFont:[UIFont systemFontOfSize:10.0f]];

[self addSubview:label];

}

}

return self;

}

-(void)setDefaultVaule:(float)value

{

defaultValue =value;

[self setNeedsDisplay];

}

-(void)setPoints:(float)value

{

[pointsArray removeAllObjects];

for (int i=0; i

[pointsArray addObject:[NSNumber numberWithFloat:value]];

}

[self setNeedsDisplay];

}

-(void)addPoint:(float)pointvalue

{

[pointsArray insertObject:@(pointvalue) atIndex:0];

[pointsArray removeObjectAtIndex:[pointsArray count] - 1];

[self setNeedsDisplay];

}

- (NSArray*)arrayOfPoints {

NSMutableArray *points = [NSMutableArray array];

int viewWidth = CGRectGetWidth(self.frame);

int viewHeight = CGRectGetHeight(self.frame);

for (int i = 0; i < [pointsArray count]; i++) {

float point1x = viewWidth - (viewWidth / ValueNum) * i;

float point1y = (viewHeight - (chartHeight / (ymax-ymin)) * [pointsArray[i] floatValue])-topOffset/2;

CGPoint p;

p = CGPointMake(point1x, point1y);

[points addObject:[NSValue valueWithCGPoint:p]];

}

return points;

}

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

// Drawing code

NSMutableArray *points = [[self arrayOfPoints] mutableCopy];

// Add control points to make the math make sense

[points insertObject:points[0] atIndex:0];

[points addObject:[points lastObject]];

UIBezierPath *lineGraph = [UIBezierPath bezierPath];

[lineGraph moveToPoint:[points[0] CGPointValue]];

for (NSUInteger index = 1; index < points.count - 2; index++)

{

CGPoint p0 = [(NSValue *)points[index - 1] CGPointValue];

CGPoint p1 = [(NSValue *)points[index] CGPointValue];

CGPoint p2 = [(NSValue *)points[index + 1] CGPointValue];

CGPoint p3 = [(NSValue *)points[index + 2] CGPointValue];

float granularity=20.0;

// now add n points starting at p1 + dx/dy up until p2 using Catmull-Rom splines

for (int i = 1; i < granularity; i++)

{

float t = (float) i * (1.0f / (float) granularity);

float tt = t * t;

float ttt = tt * t;

CGPoint pi; // intermediate point

pi.x = 0.5 * (2*p1.x+(p2.x-p0.x)*t + (2*p0.x-5*p1.x+4*p2.x-p3.x)*tt + (3*p1.x-p0.x-3*p2.x+p3.x)*ttt);

pi.y = 0.5 * (2*p1.y+(p2.y-p0.y)*t + (2*p0.y-5*p1.y+4*p2.y-p3.y)*tt + (3*p1.y-p0.y-3*p2.y+p3.y)*ttt);

[lineGraph addLineToPoint:pi];

}

[lineGraph addLineToPoint:p2];

}

[lineGraph addLineToPoint:[(NSValue *)points[(points.count - 1)] CGPointValue]];

[strokeColor setStroke];

lineGraph.lineCapStyle = kCGLineCapRound;

lineGraph.lineJoinStyle = kCGLineJoinRound;

lineGraph.flatness = 0.5;

lineGraph.lineWidth = strokeLineWidth; // line width

[lineGraph stroke];

[zeroLinestrokeColor setStroke];

UIBezierPath *zeroLine = [UIBezierPath bezierPath];

[zeroLine moveToPoint:CGPointMake(self.frame.size.width/ValueNum, self.frame.size.height/2)];

[zeroLine addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height/2)];

zeroLine.lineWidth = zeroLineWidth; // line width

[zeroLine stroke];

[unitLinestrokeColor setStroke];

for (int i=0; i<=unitNum; i++) {

UIBezierPath *unitLine = [UIBezierPath bezierPath];

[unitLine moveToPoint:CGPointMake(self.frame.size.width/ValueNum, self.frame.size.height-chartHeight/unitNum*i-topOffset/2)];

[unitLine addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height-chartHeight/unitNum*i-topOffset/2)];

unitLine.lineWidth = unitLineWidth;

[unitLine stroke];

}

}

@end

在DeviceChartViewController初始化图表类并动态显示:

//

//  DeviceChartViewController.h

//  ESPC-M-HD

//

//  Created by icarus on 15/11/26.

//  Copyright © 2015年 icarus. All rights reserved.

//

#import

@interface DeviceChartViewController : UIViewController

{

BOOL end;

}

@property (nonatomic,strong) NSString* charttitle;

@property (nonatomic,strong) NSString* statusName;

@property (nonatomic,strong) NSString* device_hash;

@property (nonatomic,strong) NSNumber* defaultValue;

@end

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

valueArray = [[NSMutableArray alloc] init];

[self.view addSubview:self.lineChart];

}

-(void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear:YES];

[self myRunloop];

}

-(void)viewWillDisappear:(BOOL)animated

{

[super viewWillDisappear:YES];

end =YES;

}

-(DSGraphChart *)lineChart{

if (!_lineChart) {

_lineChart = [[DSGraphChart alloc] initWithFrame:CGRectMake(0, 80, self.view.bounds.size.width, 400)];

[_lineChart setPoints:self.defaultValue.floatValue];

}

return _lineChart;

}

最终展示的效果:

主要说下一个坑:那就是UIView的drawrext重绘机制,刚开始做的时候,随着数据的动态变化,uiview重绘后没有清除之前的图形,导致出现了多条曲线,看遍代码找不到问题出在哪里,后来无意中发现,是没有设置uiview的backgroundColor,设置了之后就不会出现了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,802评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,109评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,683评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,458评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,452评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,505评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,901评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,550评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,763评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,556评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,629评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,330评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,898评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,897评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,140评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,807评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,339评论 2 342

推荐阅读更多精彩内容