繁体   English   中英

如何使用NSURLsession及其委托方法

[英]How to use NSURLsession and its delegate methods

我的应用程序正在使用NSURLConnection 但是现在想将其完全更改为NSURLsession 看到了很多教程,但是我不明白如何使用委托方法。 请任何人能正确解释NSURLsession和委托方法。

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

这是一个简单的网址。 如何使用NSURLsession解析并获取响应。 开发中的新功能。 谢谢前进。

您可以这样做:

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

代表方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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