簡體   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