如何使用NSURLsession及其委托方法

时间:2016-07-20 09:26:24

标签: ios objective-c iphone nsurlsession

我的应用正在使用NSURLConnection。但现在想完全改变它 NSURLsession。看了很多教程,但我不明白如何使用委托方法。请,任何人都可以正确解释NSURLsession和委托方法。

  

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

这是一个简洁的网址。如何使用NSURLsession解析并获得响应。 新的发展。谢谢你。

2 个答案:

答案 0 :(得分:3)

你可以这样做:

//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];

答案 1 :(得分:0)

    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];

委派方法:

-(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];
    });
}