NSHTTPURLResponse becomes NSURLResponse

I use if-modified-as in the HTTP header to decide if I should upload the file. The application was tested and everything was fine, but now I get errors when I ask my copy of NSHTTPURLResponse response.statusCode or [[response allHeaderFields] objectForKey:@"Last-Modified"] .

This seems to be just NSURLResponse. What are the possible reasons?

I read this section , but the problem is still not clear to me. Thank you in advance! UPD: some code:

  NSURL *url = [NSURL URLWithString:urlString]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:url]; [myRequest setHTTPMethod:@"GET"]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"; df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; [myRequest addValue:[df stringFromDate:lastModifiedLocal] forHTTPHeaderField:@"If-Modified-Since"]; myRequest.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; NSHTTPURLResponse *response=nil; NSError* error = nil; NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { NSLog(@"Error sending request: %@", [error localizedDescription]); } //As was advised NSHTTPURLResponse* newResp = (NSHTTPURLResponse*)response; //crash here NSLog(@"%d", newResp.statusCode); 

UPD: The error in the code is myRequest and the request is different variables. The problem is resolved.

+4
source share
2 answers

It is very likely that the request is not working and the response object is not created. You can check it as follows:

 if (response) { NSHTTPURLResponse* newResp = (NSHTTPURLResponse*)response; NSLog(@"%d", newResp.statusCode); } else { NSLog(@"No response received"); } 

As suggested by another commenter, you should probably include an NSError object so that you can more efficiently check for errors:

 NSHTTPURLResponse *response=nil; NSError *error = nil; NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: &error]; 

Then you can check the error before checking the response:

 if (error) { NSLog(@"Error sending request: %@", [error localizedDescription]); } 
+3
source

You can simply pounce on him:

 - (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)aResponse { self.response = (NSHTTPURLResponse *)aResponse; } 

Edit

Your answer is NULL. Try the following:

 NSHTTPURLResponse *response = nil; NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
0
source

Source: https://habr.com/ru/post/1391404/


All Articles