简体   繁体   中英

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.

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];
    NSURLSession *session=[NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask=[session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@",json);
        }];
        [dataTask resume];

Delegate Methods:

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSData *data=[NSData dataWithContentsOfURL:location];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progress.hidden=YES;
        self.image.image=[UIImage imageWithData:data];
    });
    [session finishTasksAndInvalidate];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{

}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    float progress=(double)totalBytesWritten/(double)totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.progress setProgress:progress];
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM