我正在尝试从网站获取数据以在表格视图中显示
我的代码:
-(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的情况下工作但是它会停止程序直到收到数据
答案 0 :(得分:5)
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。