{
NSURL *url = [NSURL URLWithString:KWangyiNewsAPI];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//发送异步请求建立连接,同时设置委托对象,异步请求其实是在主线程之外,开启另一个线程执行这项操作
[NSURLConnection connectionWithRequest:request delegate:self];}
{ //获取json字符串
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",json);
//解析JSON
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dic);
NSArray *arr = [dic objectForKey:@"T1348649580692"];
for (NSDictionary *obj in arr) {
News *news = [[News alloc]init];
news.imageUrl = [obj objectForKey:@"imgsrc"];
news.title = [obj objectForKey:@"title"];
news.detail = [obj objectForKey:@"lmodify"];
news.url = [obj objectForKey:@"url_3w"];
[array addObject:news];
}
[self.myTableView reloadData];
}
//下面是在加载图片到tableview上时开辟另外一个线程
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIden = @"myCell";
static BOOL nibsRegistered = NO;
if (!nibsRegistered) {
UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:cellIden];
nibsRegistered = YES;
}
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIden];
if (cell == nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIden];
}
News *news = [array objectAtIndex:indexPath.row];
//下面注释的2行本来直接在此方法里加载的,可是这会减缓加载效率,所以在加载图片是开辟了一个新的线程
// NSURL *url = [NSURL URLWithString:news.imageUrl];
// cell.NewsImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
[self loadImage:news.imageUrl withIndexPath:indexPath]; //开辟新的线程加载图片
cell.NewsTitle.text = news.title;
cell.NewsDetail.text = news.detail;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.myActivity.hidesWhenStopped = YES;
[cell.myActivity startAnimating];
return cell;
}
- (void)loadImage:(NSString *)imageUrl withIndexPath:(NSIndexPath *)indexPath
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
if (data != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
CustomCell *cell = (CustomCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = [UIImage imageWithData:data];
[cell.myActivity stopAnimating];
});
}
});
}