Reputation: 19
I wanted to know if it is possible and if so how to know the url you are accessing via objective-c takes you to the correct webpage. To elaborate further:
If a user is using an app that connects to a webpage to get it's data, and if this user is say at an airport. The internet connection at airport in many cases will redirect u to their webpage (regardless of what url u maybe type) where u have to either pay or something to get any further internet access. Thus if a app needing data from a webpage is used without user's knowledge of this limited access to internet, i want to display a popup message that informs the user saying something that the webpage it tried to access was required to a different webpage thus cannot access data. As oppose to getting false data and the user thinking the app is buggy.
Is there a way to do this. Thanks in advance for all of your help.
Upvotes: 0
Views: 337
Reputation: 101
I would say you must intercept the redirectURL and if it is the one you are expecting then continue with the redirect as expected, however if it is not the one you expected then show some message to the user rather than following the wrong redirectURL.
//This method can be used to intercept the redirect
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse {
if(redirectResponse != nil && redirectResponse) {
//Cast NSURLResponse to NSHTTPURLResponse
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) redirectResponse;
//Verify if statusCode == MOVED_TEMPORARILY (302)
if((long)[httpResponse statusCode] == 302){
NSDictionary* headers = [(NSHTTPURLResponse *)httpResponse allHeaderFields];
NSString *redirectLocation;
//Find redirect URL
for (NSString *header in headers) {
if([header isEqualToString:@"Location"]){
redirectLocation = headers[header];
break;
}
}
//return nil without following the redirect URL automatically
return nil;
} else {
//return without modifiying request
return request;
}
} else {
//return without modifiying request
return request;
}
//returnd without modifiying request
return request;
}
- (void)connection:(NSURLConnection *)aConnection
didReceiveResponse:(NSHTTPURLResponse *)aResponse
{
if ([aResponse statusCode] == 302) {
//do whatever you need to do with the response, the redirectURL is in the header "Location"
//for example show some message
}
}
Upvotes: 0
Reputation:
If you are using NSURLConnection
you can implement the NSURLConnectionDelegate
method
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
which is called if it is determined that the request must redirect to a new location. The delegate can the choose to allow the redirect, modify the destination, or deny the redirect.
You can read more about NSURLConnectionDelegate
and its methods here
Upvotes: 3