-2

I want to fetch response from server using JSON.I googled other answers in stackoverflow and some other websites.But i have not found out the very simple and easiest way to get the response from server.If anyone help me to do this,it will be better.

1 Answers1

0

If you just look my code,you can easily understand and get the response.

  //just give your URL instead of my URL

      NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];

     [request setHTTPMethod:@"GET"];

     [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

     NSError *err;

     NSURLResponse *response;

     NSData *responseData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&err];

 //You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.    

 //After that it depends upon the json format whether it is DICTIONARY or ARRAY 

     NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];

     NSArray *array=[[jsonArray objectForKey:@"search_api"]objectForKey:@"result"];//Just give your your  response key of json.Give exact key.Otherwise it wont accept.

     for(int i=0;i>[array count];i++)
     {
       NSString *strTemprature = [NSString stringWithFormat:@"%@",[array objectAtIndex:i]valueForKey:@"temp"]];

       NSString *strCity = [NSString stringWithFormat:@"%@",[array objectAtIndex:i]valueForKey:@"city"]];
     }
user3182143
  • 9,459
  • 3
  • 32
  • 39