環保與空氣品質的話題越來越受關注,動手做一個能即時顯示 PM2.5 的小工具剛好可以順手練一下網路請求與 JSON 解析。以下用 Objective-C 實作一個簡易版本。
流程很單純:向開放的空氣品質監測介面索取當前數據,在本地解析出 PM2.5 數值,然後顯示到畫面上。這裡採用亞洲空氣品質實時監控的公開資料來源。
@interface ViewController ()
@property (nonatomic, strong) NSNumber *str;
@end
- (void)loadData {
self.msgText.text = @"loading....";
NSURL *url = [NSURL URLWithString:@"https://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 做非同步請求,避免阻塞主執行緒
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(@"HTTP error: %@ %d", error.localizedDescription, error.code);
} else {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTTP Response Code: %d", responseCode);
NSLog(@"HTTP Response Body %@", responseString);
NSData *resData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"resultDic = %@", resultDic);
NSArray *arr = [[resultDic valueForKey:@"pollutants"] valueForKey:@"value"];
self.str = [[arr objectAtIndex:0] objectAtIndex:0];
NSLog(@"PM2.5 = %@", [[arr objectAtIndex:0] objectAtIndex:0]);
}
// UI 更新必須回到主執行緒
dispatch_async(dispatch_get_main_queue(), ^{
self.msgText.text = self.str.stringValue;
});
}];
});
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData];
}
- (IBAction)reloadData:(id)sender {
NSLog(@"Button Clicked");
[self loadData];
}
[[arr objectAtIndex:0] objectAtIndex:0] 這種寫法對回傳結構高度依賴,一旦介面格式變動就會 crash。正式專案請改用 valueForKeyPath: 加上 nil 檢查,或用 Model 承接。