我正在尝试从网站获取数据以在表格视图中显示

我的代码:

-(void)loadTutorials {
    NSURL *url = [NSURL URLWithString:[@"http://www.example.com/search?q=" stringByAppendingString:self.searchString]];
    NSURLRequest *UrlString = [[NSURLRequest alloc] initWithURL:url];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:UrlString
                                                          delegate:self];

    [connection start];
    NSLog(@"Started");

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
        TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:data];

        NSString *tutorialsXpathQueryString = @"//div[@id='header']/div[@class='window']/div[@class='item']/div[@class='title']/a";
        NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];

        NSMutableArray *newTutorials = [[NSMutableArray alloc] init];

        for (TFHppleElement *element in tutorialsNodes) {

            Data *tutorial = [[Data alloc] initWithTitle: [[element firstChild] content]
                                                     Url: [@"http://www.example.com" stringByAppendingString: [element objectForKey:@"href"]]
                              ];

            [newTutorials addObject:tutorial];


        }

        _objects = newTutorials;
        [self.tableView reloadData];


}


但是没有显示数据,是否没有完成加载?
我在没有NSURLConnection的情况下可以正常工作,但是它将停止程序,直到接收到数据

最佳答案

根据NSURLConnectionDataDelegate

connection:didReceiveData:


以递增方式调用。


  新可用的数据。代表应合并内容
  交付的每个数据对象的数量,以构建URL的完整数据
  加载。


因此,这意味着您应该在此方法内附加新数据。

然后,在

- (void)connectionDidFinishLoading:(NSURLConnection *)connection


您应该操纵您的数据。

因此,例如

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // Create space for containing incoming data
    // This method may be called more than once if you're getting a multi-part mime
    // message and will be called once there's enough date to create the response object
    // Hence do  a check if _responseData already there
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data
    [_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Parse the stuff in your instance variable now
}


显然,您还应该实现负责错误处理的委托。

一个简单的注释如下。如果数据太大,并且您需要做一些计算工作(例如解析),则可以阻止UI。因此,您可以将解析移到另一个线程中(GCD是您的朋友)。然后,完成后,您可以在主线程中重新加载表。

也可以在此处查看更多信息:NSURLConnectionDataDelegate order of functions

关于ios - NSURLConnection didReceiveData没有加载数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20923142/

10-10 21:14
查看更多