网易新闻——多线程的改进

#import "WhyMainViewController.h"
#define kWangyiHeadNewsAPI @"http://c.m.163.com/nc/article/headline/T1348649580692/0-20.html"
#import "News.h"
#import "NewsCell.h"

@interface WhyMainViewController ()
{
    //新闻集合
    NSMutableArray *newsArray;
}

-(void)loadNewsData;

@end

@implementation WhyMainViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    newsArray = [NSMutableArray array];
    
    //加载新闻数据
    [self loadNewsData];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
#pragma mark - 加载新闻数据
-(void)loadNewsData
{
    //创建URL对象
    NSURL *url = [NSURL URLWithString:kWangyiHeadNewsAPI];
    
    //创建Request请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setURL:url];
    
    //发送异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //处理响应
        if (connectionError != nil) {
            NSLog(@"fail!%@",connectionError.localizedDescription);
        }
        else{
            //成功返回数据,解析JSON数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
            NSArray *arr = [dic objectForKey:@"T1348649580692"];
            for (NSDictionary *objDic in arr) {
                //获取每一条新闻信息
                News  *n = [[News alloc]init];
                n.title = [objDic objectForKey:@"title"];
                n.detailUrl = [objDic objectForKey:@"url_3w"];
                n.imageUrl = [objDic objectForKey:@"imgsrc"];
                n.timeConsuming = [objDic objectForKey:@"lmodify"];
                
                //将当前创建的对象添加到数据源
                [newsArray addObject:n];
            }
            
            //刷新TableVIEW
            [self.tableView reloadData];
            
        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [newsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NewsCell";
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.tag = 100 + [indexPath row];
    
    // Configure the cell...
    News *n = [newsArray objectAtIndex:[indexPath row]];
    cell.timeLable.text = n.timeConsuming;
    cell.titleLable.text = n.title;
    
    //加载图片
//    NSURL *url = [NSURL URLWithString:n.imageUrl];
//    NSData *data = [[NSData alloc]initWithContentsOfURL:url];
//    UIImage *image = [UIImage imageWithData:data];
//    
//    cell.headerImageView.image = image;
    
    //开启新的线程加载图片
    [self loadImage:n.imageUrl andIndexPath:indexPath];
    
    return cell;
}

-(void)loadImage:(NSString *)urlPath
    andIndexPath:(NSIndexPath *)indexPath
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //加载图片
        
        NSURL *url = [NSURL URLWithString:urlPath];
        NSData *data = [[NSData alloc]initWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        //保存到沙盒中
        if(image != nil){
            dispatch_async(dispatch_get_main_queue(), ^{
                NewsCell *cell = (NewsCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.headerImageView.image = image;
            });
        }
    });
}

#pragma mark - 在segue跳转之前自动调用一个方法,一般做参数传递
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"detailSegue"]) {
        //传递参数
        UIViewController *detail = segue.destinationViewController;
        
        NewsCell *cell = (NewsCell *)sender;
        NSInteger row = cell.tag - 100;
        News *n = [newsArray objectAtIndex:row];
        
        [detail setValue:n.detailUrl forKey:@"detailUrl"];
    }

}



//下一个页面.h页面

#import <UIKit/UIKit.h>

@interface WhyViewController : UIViewController
<UIWebViewDelegate>
//详情页面请求的url地址
@property (copy, nonatomic)NSString *detailUrl;
@property (weak, nonatomic) IBOutlet UIWebView *detailWebView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicator;

@end

//下个页面.m页面

#import "WhyViewController.h"

@interface WhyViewController ()

@end

@implementation WhyViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"%@",self.detailUrl);
    NSURL *url = [NSURL URLWithString:self.detailUrl];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    [self.detailWebView loadRequest:request];
    self.detailWebView.delegate = self;
    
    self.indicator.hidesWhenStopped = YES;
}

-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.indicator startAnimating];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.indicator stopAnimating];
    
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值