I am trying to use a location-based Weather app and it is crashing as soon as I open the view for that page.
This is the method;
- (WeatherModel *) parseWeatherData: (NSData *) data {
WeatherModel *weatherModel = [[WeatherModel alloc] init];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: &error];
if (error) {
NSLog(@"Error decoding JSON data : %@", error.localizedDescription);
[self->_delegate didFailedWithError: error];
return nil;
}
if ([jsonObject isKindOfClass: [NSDictionary class]]) {
NSMutableDictionary *dicJsonObject = [[NSMutableDictionary alloc] initWithDictionary: jsonObject];
NSString *cityName = [dicJsonObject valueForKey: @"name"];
double temperature = [[[dicJsonObject valueForKey: @"main"] valueForKey: @"temp"] doubleValue];
NSMutableArray *arrWeatherData = [[NSMutableArray alloc] initWithArray: [dicJsonObject valueForKey: @"weather"]];
weatherModel.strCityName = cityName;
weatherModel.temperature = temperature;
weatherModel.weatherConditionID = [[[arrWeatherData objectAtIndex: 0] valueForKey: @"id"] intValue];
}
return weatherModel;
}
It is crashing on this line;
if (error) {
NSLog(@"Error decoding JSON data : %@", error.localizedDescription);
[self->_delegate didFailedWithError: error];
return nil;
}
If I comment out the NSLog
section and [self->_delegate didFailedWithError: error];
the app does not crash, but then does not function as expected either...
The second part of the crash using debug is here;
- (void) fetchWeatherForCity: (NSString *) cityName {
_strWeatherURL = [NSString stringWithFormat: @"https://api.openweathermap.org/data/2.5/weather?q=%@&appid=bfea07812845ff9cb7e", cityName];
NSURL *weatherURL = [[NSURL alloc] initWithString: _strWeatherURL];
NSURLSessionConfiguration *urlSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration: urlSessionConfiguration];
NSURLSessionDataTask *task = [urlSession dataTaskWithURL: weatherURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"Error fetching weather data : %@", error);
[self->_delegate didFailedWithError: error];
return;
}
WeatherModel *weatherModel = [[WeatherModel alloc] init];
weatherModel = [self parseWeatherData: data];
if (weatherModel != nil) {
[self->_delegate didUpdateWeather: weatherModel];
}
}];
[task resume];
}
On this line;
weatherModel = [self parseWeatherData: data];