简体   繁体   English

使用NSURLSession下载数据并进行异步处理

[英]Downloading data and processing asynchronous with NSURLSession

I am using NSURLSession to download xml files and then I want to do different processing to this files, like parsing them: 我正在使用NSURLSession下载xml文件,然后要对此文件进行不同的处理,例如解析它们:

-(void)parseFeed:(NSURL *)url
{
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];

    NSURLSessionDataTask* task = [FeedSessionManager.sharedManager.session dataTaskWithRequest:request completionHandler:^(NSData* data, NSURLResponse* response, NSError* error)
                                  {
                                      Parser* parser = [[Parser alloc] initWithData:data];

                                      [self.feeds addObjectsFromArray:[parser items]];

                                  }];

    [task resume];
}

Parser object will parse the xml file using NSXMLParser . 解析器对象将使用NSXMLParser解析xml文件。 The parseFeed:(NSURL*)url is called from the ViewController : ViewController调用parseFeed:(NSURL*)url

Downloader* downloader = [[Downloader alloc] init];
[downloader parseFeed:[NSURL URLWithString:@"http://www.engadget.com/tag/features/rss.xml"]];
NSArray* items = [downloader feeds];

And this is how I create the NSURLSession object: 这就是我创建NSURLSession对象的方式:

-(id)init
{
    if(self = [super init])
    {
        _session = [NSURLSession sessionWithConfiguration:FeedSessionConfiguration.defaultSessionConfiguration delegate:self delegateQueue:nil];
    }

    return self;
}

Of course this approach doesn't work for me. 当然,这种方法对我不起作用。 Inside parseFeed method I want to wait until all data is downloaded and processed. parseFeed方法内部,我想等待所有数据下载并处理parseFeed Only then I want to access the self.feeds array in the ViewController . 只有这样,我才想访问ViewControllerself.feeds数组。

Can someone point me into the right direction into doing this ? 有人可以指出我这样做的正确方向吗? Or maybe point me to a different approach ? 还是让我指出了另一种方法?

I have used ASIHTTPRequest but now no longer maintained but you can use AFHTTPClient's operation queue 我使用了ASIHTTPRequest,但现在不再维护,但是可以使用AFHTTPClient的操作队列

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:nil];

// Important if only downloading one file at a time
[client.operationQueue setMaxConcurrentOperationCount: 1];

NSArray *videoURLs; // An array of strings you want to download

for (NSString * videoURL in videoURLs) {

    // …setup your requests as before

    [client enqueueHTTPRequestOperation:downloadRequest];
}

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

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