Wednesday, May 1, 2013

NSURLConnection canHandleRequest example ios


Returns whether a request can be handled based on a preflight evaluation.
+ (BOOL)canHandleRequest:(NSURLRequest *)request
Parameters of [NSURLConnection canHandleRequest]
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@""];
    [[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);

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

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


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


 -(void) httpDataDidFailLoadingWithReason:(NSString*)reason

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