Search code examples
iosjsonobjective-c

Handling a JSON String After API GET Request on iOS


I am using a free weather API for an app. All I really need from the output is forecasted Low Temp, Forecasted High Temp, and conditions. In my app I set up the NSURLConnection and everything, and it works fine. My code is:

-(IBAction) weatherView {
                           
    NSString *bringitalltogether = @"http://api.worldweatheronline.com/free/v1/weather.ashx?q=79201&format=json&key=22gxkzqxwjvzxp44e3wvdp2c";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
    [request setHTTPMethod:@"GET"];
            
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    [connection release];

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"RESPONSE%@", response);
    if ([response isKindOfClass:[NSHTTPURLResponse class]])
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
        //If you need the response, you can use it here
        int code = [httpResponse statusCode];
        NSLog(@"%i", code);
        if (code == 200){
            
        }
        
        else
        {
            UIAlertView *oops = [[UIAlertView alloc] initWithTitle:@"Oops" message:@"The weatherman is having difficulties getting you the forecast.  Please check your network settings and try again later." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [oops show];
            [oops release];
        }
        
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSMutableDictionary *allResults = [NSJSONSerialization
                                       JSONObjectWithData:data
                                       options:NSJSONReadingAllowFragments
                                       error:nil];
    NSLog(@"Data was received%@", allResults.description);

    
}

Everything seems to work great, I just don't know where to turn to from here to take from the JSON string output and weed out only what I actually need.

The output that I receive is:

{
    data =     {
        "current_condition" =         (
                        {
                cloudcover = 0;
                humidity = 19;
                "observation_time" = "05:57 PM";
                precipMM = "0.0";
                pressure = 1005;
                "temp_C" = 22;
                "temp_F" = 72;
                visibility = 16;
                weatherCode = 113;
                weatherDesc =                 (
                                        {
                        value = Sunny;
                    }
                );
                weatherIconUrl =                 (
                                        {
                        value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png";
                    }
                );
                winddir16Point = WNW;
                winddirDegree = 300;
                windspeedKmph = 35;
                windspeedMiles = 22;
            }
        );
        request =         (
                        {
                query = 79201;
                type = Zipcode;
            }
        );
        weather =         (
                        {
                date = "2014-02-28";
                precipMM = "0.0";
                tempMaxC = 25;
                tempMaxF = 77;
                tempMinC = 2;
                tempMinF = 35;
                weatherCode = 113;
                weatherDesc =                 (
                                        {
                        value = Sunny;
                    }
                );
                weatherIconUrl =                 (
                                        {
                        value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png";
                    }
                );
                winddir16Point = NW;
                winddirDegree = 307;
                winddirection = NW;
                windspeedKmph = 33;
                windspeedMiles = 20;
            }
        );
    };
}

Solution

  • here your code

    // get data
    NSDictionary *getData = [allResults objectForKey:@"data"];
    NSArray *currentConditions = [getData objectForKey:@"current_condition"];
    NSArray *weathers = [getData objectForKey:@"weather"];
    
    NSDictionary *currentCondition = [currentConditions objectAtIndex:0];
    NSLog(@"current temp = %@", [currentCondition objectForKey:@"temp_C"]);
    
    NSDictionary *weather = [weathers objectAtIndex:0];
    NSLog(@"hight temp = %@", [weather objectForKey:@"tempMaxC"]);
    NSLog(@"low temp = %@", [weather objectForKey:@"tempMinC"]);