Wednesday, May 1, 2013

NSURLConnection connectionWithRequest example ios


connectionWithRequest :delegate:

Creates and returns an initialized URL connection and begins to load the data for the URL request.
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate
Parameters of [NSURLConnection connectionWithRequest]
request
The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.[NSURLConnection connectionWithRequest]
delegate
The delegate object for the connection. The delegate will receive delegate messages as the load progresses. Messages to the delegate will be sent on the thread that calls this method. For the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode.
Return Value of [NSURLConnection connectionWithRequest]
The URL connection for the URL request. Returns nil if a connection can't be created.
Special Considerations
During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.
Example of [NSURLConnection connectionWithRequest]
    //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 connectionWithRequest]
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:articleURL]];

    if ([NSURLConnection canHandleRequest:request] && reachable) {
        // Set up an asynchronous load request
        conn = [NSURLConnection connectionWithRequest:request delegate:self];
        loadCancelled = NO;
        if (conn) {
            NSLog(@" ARTICLE is REACHABLE!!!!");
            self.articleData = [NSMutableData data];
        }
    }