0

我正在使用 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 对象将使用NSXMLParser. 是从以下parseFeed:(NSURL*)url位置调用的ViewController

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

这就是我创建NSURLSession对象的方式:

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

    return self;
}

当然,这种方法对我不起作用。内部parseFeed方法我想等到所有数据都下载并处理完毕。只有这样我才想self.feeds访问ViewController.

有人可以指出我这样做的正确方向吗?或者也许指向我不同的方法?

4

1 回答 1

1

我曾经使用过 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];
}
于 2013-12-27T10:35:47.577 回答