Skip to content

Instantly share code, notes, and snippets.

@bebus77
Created December 4, 2014 21:19
Show Gist options
  • Save bebus77/030157d2eb1f104a15e4 to your computer and use it in GitHub Desktop.
Save bebus77/030157d2eb1f104a15e4 to your computer and use it in GitHub Desktop.
Download weather forecast #AppSoc02122014
- (void)downloadWeatherForecast {
// constant representing the number of seconds in a day
const int kSecondsInDay = 60 * 60 * 24;
// the url of the weather api
NSString *const kWeatherForecastURL = @"http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=14";
// create a url request for the weather api url
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:kWeatherForecastURL]];
// send the request without blocking the main ui thread
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// exit if there is a connection error
if (connectionError) {
return;
}
NSError *error;
// parse the json response
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
// if there was a parsing error (invalid json) then exit
if (error) {
return;
}
// date formatter to get the day name from a date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
// for each weather forecast store the day
for (int i = 0; i < [json[@"list"] count]; i++) {
NSMutableDictionary *dayInfo = [NSMutableDictionary dictionary];
dayInfo[@"name"] = [dateFormatter stringFromDate:[[NSDate date] dateByAddingTimeInterval: kSecondsInDay * i]];
dayInfo[@"forecast"] = json[@"list"][i];
[self.daysWeather addObject:dayInfo];
}
// refresh the content of the table view
[self.tableView reloadData];
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment