您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

動手做一個 PM2.5 空氣品質監控 App(Objective-C 版)

編輯:iOS 開發綜合

環保與空氣品質的話題越來越受關注,動手做一個能即時顯示 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];
}

幾個值得改進的地方

  • 範例中把 NSNumber 宣告成類別屬性再跨執行緒讀寫,實務上應該改用 block 內的區域變數,並在主執行緒中一次完成 UI 更新。
  • [[arr objectAtIndex:0] objectAtIndex:0] 這種寫法對回傳結構高度依賴,一旦介面格式變動就會 crash。正式專案請改用 valueForKeyPath: 加上 nil 檢查,或用 Model 承接。
  • HTTP 明文介面在 iOS 上會受 ATS 限制,正式上線應改用 HTTPS,或在 Info.plist 中明確設定例外並說明理由。
  • 請求失敗時應該給使用者可讀的錯誤提示,而不是只顯示 loading。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved