NSURLConnection didReceiveData没有加载数据

Ver*_*dus 0 asynchronous objective-c nsurlconnection ios

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

我的代码:

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


}
Run Code Online (Sandbox Code Playgroud)

但是数据没有显示,数据是否未完成加载?我让它在没有NSURLConnection的情况下工作但是它会停止程序直到收到数据

Lor*_*o B 5

根据 NSURLConnectionDataDelegate

connection:didReceiveData:
Run Code Online (Sandbox Code Playgroud)

以递增方式调用.

新提供的数据.委托应该连接每个传递的数据对象的内容,以构建URL加载的完整数据.

所以这意味着你应该在这个方法中附加新数据.

然后,在

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
Run Code Online (Sandbox Code Playgroud)

你应该操纵你的数据.

所以,例如

- (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    
}
Run Code Online (Sandbox Code Playgroud)

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

一个简单的说明如下.如果数据太大而您需要进行一些计算(例如解析),则可能会阻止UI.所以,你可以在另一个线程中移动解析(GCD是你的朋友).然后完成后,您可以在主线程中重新加载表.

另请查看更多信息:NSURLConnectionDataDelegate函数顺序.