objective c - NSTimer? - Check Connection iOS -
i using following method check if app has connection. it's simple , works great needs.
+ (void)checkinternet:(connection)block { nsurl *url = [nsurl urlwithstring:@"http://www.google.com/"]; nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url]; request.httpmethod = @"head"; request.cachepolicy = nsurlrequestreloadignoringlocalandremotecachedata; request.timeoutinterval = 10.0; [nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue mainqueue] completionhandler: ^(nsurlresponse *response, nsdata *data, nserror *connectionerror) { block([(nshttpurlresponse *)response statuscode] == 200); }]; }
however, i'd if status doesn't return 200, i'd check again, @ least couple of times. what's best way 1 second intervals?
below how i'm calling above method.
[self checkinternet:^(bool internet) { if (internet) { // "internet" aka google } else { // no "internet" aka no google } }];
i use reachability detecting general network connection issues (see end of answer). use following method executing retries.
- (void)performselector:(sel)aselector withobject:(id)anargument afterdelay:(nstimeinterval)delay;
you adapt system following have new class method has optional number of retries.
nb. not tested following. give general idea.
// variable track number of retries left. if had shared instance // property easier. static nsuinteger maxconnectiontries = 0; // new method lets pass retry count. + (void)checkinternet:(connection)block withmaxtries:(nsuinteger)maxtries { maxconnectiontries=maxtries; [self checkinternet:block]; } // original code extended retry calling when code 200 // seen on delay of 1s. defaults old code when retry limit exceeded // or non 200 code received. + (void)checkinternet:(connection)block { nsurl *url = [nsurl urlwithstring:@"http://www.google.com/"]; nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url]; request.httpmethod = @"head"; request.cachepolicy = nsurlrequestreloadignoringlocalandremotecachedata; request.timeoutinterval = 10.0; [nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue mainqueue] completionhandler: ^(nsurlresponse *response, nsdata *data, nserror *connectionerror) { if ([(nshttpurlresponse *)response statuscode] != 200 && maxconnectionretries > 0){ maxconnectionretries--; [self performselector:@selector(checkinternet:) withobject:block afterdelay:1.0]; } else{ maxconnectionretries = 0; block([(nshttpurlresponse *)response statuscode] == 200); } }]; }
for general detection of internet connectivity, best use reachability. see here.
i start reachability handler appdelegate code , publish local notifications when connectivity changes occur. allows application receive connection change notification , transient view controllers within viewwillappear
, viewwilldisappear
register , deregister local notifications if interested in connection changes.
Comments
Post a Comment