網路請求是行動應用的核心能力之一。以下程式碼示範如何向天氣服務的 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,建議改用異步方式處理。