iOS版本PM2.5空气质量监控仪

前言

鉴于柴静版《苍穹之下》的火爆,或许更多的人会关心环境,空气质量等环保因素,参考某学院的Swift版本的PM2.5的获取,本人自己写个Objective-C版本的。

基本原理

从服务器获取当前的空气质量数据,气象中心开放接口亚洲空气质量实时监控, 参照人家的教程使用亚洲空气质量监控。
本地解析数据,获取PM2.5数值,进行显示。

具体实现
NSNumber *str;

-(void) loadData{
self.msgText.text = @"loading....";
NSURL *url = [NSURL URLWithString:@"http://aqicn.org/publishingdata/json"];
NSString *post=@"postData";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[request setTimeoutInterval:10.0];

//GCD实现异步接口通信与UI更新的同步
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request
        queue:queue
        completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
        if (error) {
            NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);
        }else{
            NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"HttpResponseCode:%d", responseCode);
            NSLog(@"HttpResponseBody %@",responseString);
            NSData *resData = [[NSData alloc] initWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding]];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"resultDic=%@", resultDic);

            arr = [[resultDic valueForKey:@"pollutants"] valueForKey:@"value"];
            str = [[arr objectAtIndex:0] objectAtIndex:0];
            NSLog(@"PM2.5=%@", [[arr objectAtIndex:0] objectAtIndex:0]);
        }
    }];
        dispatch_async(dispatch_get_main_queue(),^{
    self.msgText.text = str.stringValue;
        });
    });
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self loadData];
// start reloadData
}
- (IBAction)reloadData:(id)sender {
NSLog(@"Button Clicked");
[self loadData];
NSLog(@"Button Clicked");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

详情请参考如下链接:
源码地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钱国正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值