I wrote the GET method code to retrieve the details from server(json format).But I am getting the error (the operation could not be completed). can anyone please provide me some information regarding this? My code:
-(void)getResponseWithOutBodywithMethod:(NSString*)method
{
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:method];
//[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// [request setTimeoutInterval:20.0];
NSURLConnection *conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData alloc] init] ;
}
}
#pragma mark NSURLConnection delegate methods
- (void) connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response{
/* This method is called when the server has determined that it has
enough information to create the NSURLResponse. It can be called
multiple times, for example in the case of a redirect, so each time
we reset the data. */
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData: ( NSData *)data{
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:( NSError *)error{
completion(nil, error);
NSLog(@"%@",[error localizedDescription]);
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
if (receivedData != nil) {
NSError *jsonParsingError = nil;
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData
options:kNilOptions error:&jsonParsingError];
NSString* str = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"error %@",jsonParsingError.localizedDescription);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"ER" message:str delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
if (dict == nil && [dict count]==0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:jsonParsingError.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
completion(nil, jsonParsingError);
}
else {
completion(dict, nil);
}
}
else {
completion(nil, [NSError errorWithDomain:@"http" code:-1 userInfo:nil]); //todo proper error
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to get data." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}
}