Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get http response code in ios when using sendSynchronousRequest [duplicate]

Tags:

ios

iphone

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?

like image 276
Adam Knights Avatar asked Mar 09 '26 17:03

Adam Knights


1 Answers

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
}
like image 157
Vladimir Avatar answered Mar 12 '26 07:03

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!