saravanar saravanar - 4 months ago 15
iOS Question

How to use NSURLsession and its delegate methods

My app running is using

NSURLConnection
. But now want to change it completely to
NSURLsession
. Saw lots of tutorials but I can't understand how to use the delegate methods. Please, can any one explain properly that
NSURLsession
and the delegate methods.


http://api.kivaws.org/v1/loans/search.json?status=fundraising


This is a sampl url. how can I parse and get the response using
NSURLsession
.
New in development. Thanks advance.

Answer

YOU CAN DO LIKE THIS:

//GET REQUEST CODE
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    // NSURLSession *s = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"PUT_YOUR_URL"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (data) {
            NSHTTPURLResponse * httpResponse  = (NSHTTPURLResponse*)response;
            NSInteger statusCode = httpResponse.statusCode;
            if (statusCode == 200) {
               //PERFORM YOUR OPERATIONS
            }
        }else if (error)
        {
            NSLog(@"Errorrrrrrr....");
        }

    }];
    [dataTask resume];
Comments