NSURLConnection下载独立于ViewController

1.首先定义一个协议


//  HttpDownloadDelegate.h

#import <Foundation/Foundation.h>


@class HttpDownload;


@protocol HttpDownloadDelegate <NSObject>


- (void)downloadComplete:(HttpDownload *)hd;


@end


2.定义下载类

//  HttpDownload.h

#import <Foundation/Foundation.h>

#import "HttpDownloadDelegate.h"


@interface HttpDownload : NSObject

<NSURLConnectionDataDelegate>

{

    NSURLConnection *mConnection;

    

    NSMutableData *_mData;

    

    id <HttpDownloadDelegate> _delegate;

    

}


@property (nonatomic,assign) id <HttpDownloadDelegate> delegate;

@property (nonatomic,readonly) NSMutableData *mData;


- (void)downloadFromUrl:(NSURL *)url;


@end


//  HttpDownload.m

#import "HttpDownload.h"


@implementation HttpDownload


@synthesize delegate,mData;


//从指定网址下载数据

- (void)downloadFromUrl:(NSURL *)url

{

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    

    mConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    mData = [[NSMutableData alloc] init];

}


#pragma mark - NSURLConnectionDataDelegate协议中的方法


//收到服务器响应

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    //清除旧数据

    [mData setLength:0];

}


//接收数据

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [mData appendData:data];

}


//下载完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    //是否能响应指定的方法

    if ([delegate respondsToSelector:@selector(downloadComplete:)]) {

        [delegate downloadComplete:self];

    }

}


//下载失败

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"下载失败");

}


@end


3.RootViewController中实现定义的HttpDownloadDelegate协议

//  RootViewController.h

#import <UIKit/UIKit.h>

#import "HttpDownloadDelegate.h"

#import "HttpDownload.h"


@interface RootViewController : UIViewController

<HttpDownloadDelegate,UITableViewDelegate,UITableViewDataSource>

{

    //用于保存用户信息

    NSMutableArray *dataArray;

    

    //用于显示下载数据

    UITableView *mTableView;

}


@end


//  RootViewController.m

#import "RootViewController.h"

#import "UserItem.h"

#import "HttpDownload.h"


@implementation RootViewController


- (void)viewDidLoad

{

    [super viewDidLoad];

    

    dataArray = [[NSMutableArray alloc] initWithCapacity:0];

    

    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];

    mTableView.dataSource = self;

    mTableView.delegate = self;

    

    [self.view addSubview:mTableView];

    [mTableView release];

    

    HttpDownload *httpDownload = [[HttpDownload alloc] init];

    

    httpDownload.delegate = self;

    

    NSString *url = @"http://192.168.88.8/sns/my/user_list.php?page=1&number=20";

    [httpDownload downloadFromUrl:[NSURL URLWithString:url]];

}



#pragma mark - HttpDownloadDelegate协议中的方法


- (void)downloadComplete:(HttpDownload *)hd

{

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:hd.mData options:NSJSONReadingMutableContainers error:nil];

    

    if (dict) {

        NSArray *userArray = [dict objectForKey:@"users"];

        for (NSDictionary *dict in userArray) {

            UserItem *item = [[UserItem alloc] init];

            item.username = [dict objectForKey:@"username"];

            item.realname = [dict objectForKey:@"realname"];

            item.uid = [dict objectForKey:@"uid"];

            item.headimage = [NSString stringWithFormat:@"http://192.168.88.8/sns%@",[dict objectForKey:@"headimage"]];

            [dataArray addObject:item];

            [item release];

        }

    }

    [mTableView reloadData];

}


#pragma mark - UITableViewDatasource协议中的方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [dataArray count];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *cellID = @"myCell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID] autorelease];

    }

    

    UserItem *item = [dataArray objectAtIndex:indexPath.row];

    

    cell.textLabel.text = item.username;

    return cell;

}


@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值