gpt4 book ai didi

ios - NSURLConnection didReceiveData 未加载数据

转载 作者:行者123 更新时间:2023-11-28 18:34:53 25 4
gpt4 key购买 nike

我正在尝试从网站获取数据以将其显示在表格 View 中

我的代码:

-(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:

以增量方式调用。

The newly available data. The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load.

所以这意味着您应该在此方法中附加新数据。

然后,在

- (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
}

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

下面是一个简单的注释。如果数据太大并且你需要做一些计算(例如解析),你可以阻止 UI。所以,你可以在不同的线程中移动解析(GCD 是你的 friend )。完成后,您可以在主线程中重新加载表格。

也可以在这里查看更多信息:NSURLConnectionDataDelegate order of functions .

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com