I currently have an ap that attempts to open a webview based on certain servers I am communicating with.
However, I allow the user the capability to type in their own server IPs in case both the iphone/ipad and server(or other device) are not on the same network. However, I am attempting to use NSURLConnection to detect if I can open a connection with the given IP however NSURLConnection never returns an error, even if the server address(or even a random web address) is completely bogus.
the .h
@interface DetailViewController : UIViewController <UIPopoverControllerDelegate, UISplitViewControllerDelegate, UITableViewDataSource, UITableViewDelegate,UIWebViewDelegate, NSURLConnectionDataDelegate> {
the relevant code in the .m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
dev_ip = @"http://www.asdfasfdfa.com/";
//dev_ip = (random ip)
NSMutableURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:dev_ip]];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
NSLog(@"Connection established");
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"No Device at designated IP"]
delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
this if/else always outputs ‘Connection established.’ Is this something NSURLConnection should not be used for? If so, what can I use to detect devices at given IP’s for connectivity. I need to stop the user from attempting to connect to bad IP’s so whats the best method in doing so?
NSURLConnection, when used with delegation, will call delegate methods when it connects, fails to connect and receive data. You should look into NSURLConnectionDelegate.
Here’s a quick example:
EDIT You actually need both delegates.
Also, just throwing it out there too, you don’t necessarily have to use an asynchronous call. You can send a synchronous call which doesn’t require you to implement a delegate. Here’s how:
You can check the response value and errors.