Wednesday, May 1, 2013

NSURLConnection canHandleRequest example ios


canHandleRequest:

Returns whether a request can be handled based on a preflight evaluation.
+ (BOOL)canHandleRequest:(NSURLRequest *)request
Parameters of [NSURLConnection canHandleRequest]
request
The request to evaluate. When created, an NSURLConnection performs a deep-copy of the request.
Return Value of [NSURLConnection canHandleRequest]
YES if a preflight operation determines that a connection with request can be created and the associated I/O can be started, NO otherwise.
Discussion of [NSURLConnection canHandleRequest]
The result of this method is valid as long as no NSURLProtocol classes are registered or unregistered, and request remains unchanged. Applications should be prepared to handle failures even if they have performed request preflighting by calling this method.
Example of [NSURLConnection canHandleRequest]
    //Create a NSURLConnection and start it
-(void) begin {
    NSURL* url = [NSURL URLWithString@"https://some.domain.com/some/path/?some=query"];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyNever];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    if ([NSURLConnection canHandleRequest:request]) {
        NSURLConnection* connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];
        hasSeenResponse = NO;
        [connection start];
    }
}     
Example of [NSURLConnection canHandleRequest]
SCNetworkReachabilityFlags flags;

 SCNetworkReachabilityRef reachability=SCNetworkReachabilityCreateWithName(NULL, [@"your        web sevice url" UTF8String]);

SCNetworkReachabilityGetFlags(reachability, &flags);
BOOL reachable=!(flags & kSCNetworkReachabilityFlagsConnectionRequired);

CFRelease(reachability);
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];


if([NSURLConnection canHandleRequest:request] && reachable)
 { 
conn=[NSURLConnection connectionWithRequest:request delegate:self];

if(conn)
{
    ////        

}
else
{
    [_delegate performSelector:@selector(httpDataDidFailLoadingWithReason:) 
                    withObject:@"No Internet Connection"    afterDelay:0.1];
 }

 }


 -(void) httpDataDidFailLoadingWithReason:(NSString*)reason
 {

UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"abc" 
                                                   message:reason
                                                   delegate:self cancelButtonTitle:@"OK"
                                           otherButtonTitles:nil];
[alertView show];
[alertView release];

  }