您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

用 NSURLConnection 抓取網路天氣預報資料

編輯:iOS 技巧大全
[摘要]本文示範如何透過 NSURLConnection 發送同步請求抓取網路 JSON 天氣資料,並用 NSJSONSerialization 解析輸出城市、日期與氣溫,是學習 iOS 網路請求與 JSON 解析的實用範例。

網路請求是行動應用的核心能力之一。以下程式碼示範如何向天氣服務的 API 發送請求,抓取徐家匯的天氣預報資料並解析顯示:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self getWeatherInfo]; } //獲得徐家匯的天氣預報 -(void)getWeatherInfo{ NSError *error; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://m.weather.com.cn/data/101021200.html" ]];//代碼為徐家匯 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error]; NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"]; NSLog(@"天氣%@",[NSString stringWithFormat:@"\n%@\n%@\n%@\n%@\n%@\n ", [weatherInfo objectForKey:@"city"],[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]); } 

輸出:

2015-03-11 16:02:06.686 徐家匯天氣預報[5526:214455] 天氣

徐家匯

2014年3月4日

星期二

小雨轉多雲

11℃~6℃

整個流程分為三個步驟:先用 NSURLRequest 建立請求、以 NSURLConnection 的 sendSynchronousRequest 發送同步請求取得回應資料,再用 NSJSONSerialization 將 JSON 資料解析成字典,最後依序取出城市、日期、星期、天氣與氣溫等欄位。需要注意的是,同步請求會阻塞當前執行緒,在實際專案中若要避免卡住 UI,建議改用異步方式處理。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved