2

I have a working http GET without using any third party bits, I am new to iOS so this was a struggle to setup initially. My code looks like:

-(NSString *) SendGetRequestToRest:(NSString *)urlEndString
{

NSString *userName = @"userN";
NSString *password = @"PassW";

NSString *urlBaseString = @"http://someurl.co.uk/";

NSString *urlString = [NSString stringWithFormat:@"%@%@", urlBaseString, urlEndString];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:urlString]];

[request setHTTPMethod:@"GET"];

NSString *str1 = [NSString stringWithFormat:@"%@:%@", userName, password];
NSString *encodedString = [self stringByBase64EncodingWithString:str1];
[request addValue:[NSString stringWithFormat:@"Basic %@",encodedString] forHTTPHeaderField:@"Authorization"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"str: %@", str);

return str;

}

What I need to do is track when the status code of the http GET is not a nice 200, I saw How to check status of web server in iOS? and this looks promising i.e. add this:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    if ([response statusCode] == 404)
    {
    /// do some stuff
    }
}

But I cant see how to connect this up to

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

as it doesnt accept a delegate?

Community
  • 1
  • 1
Adam Knights
  • 2,141
  • 1
  • 25
  • 48

1 Answers1

12

You can use returningResponse parameter to get "response":

NSHTTPURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if ([response statusCode] == 404)
{
   // Do whatever you want to do after getting response
}
Balaji Kandasamy
  • 4,446
  • 10
  • 40
  • 58
Vladimir
  • 170,431
  • 36
  • 387
  • 313