NSURLConnection下载独立于ViewController

来源:互联网 发布:大数据相关专业 编辑:程序博客网 时间:2024/05/08 02:01

1.首先定义一个协议


//  HttpDownloadDelegate.h

#import <Foundation/Foundation.h>


@classHttpDownload;


@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 = [[NSURLRequestalloc] initWithURL:url];

    

    mConnection = [[NSURLConnectionalloc] initWithRequest:requestdelegate:self];

    mData = [[NSMutableDataalloc] init];

}


#pragma mark - NSURLConnectionDataDelegate协议中的方法


//收到服务器响应

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

{

    //清除旧数据

    [mDatasetLength:0];

}


//接收数据

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

{

    [mDataappendData:data];

}


//下载完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

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

    if ([delegaterespondsToSelector:@selector(downloadComplete:)]) {

        [delegatedownloadComplete: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

{

    [superviewDidLoad];

    

    dataArray = [[NSMutableArrayalloc] initWithCapacity:0];

    

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

    mTableView.dataSource =self;

    mTableView.delegate =self;

    

    [self.viewaddSubview:mTableView];

    [mTableViewrelease];

    

    HttpDownload *httpDownload = [[HttpDownloadalloc] init];

    

    httpDownload.delegate =self;

    

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

    [httpDownloaddownloadFromUrl:[NSURLURLWithString:url]];

}



#pragma mark - HttpDownloadDelegate协议中的方法


- (void)downloadComplete:(HttpDownload *)hd

{

    NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:hd.mDataoptions:NSJSONReadingMutableContainerserror:nil];

    

    if (dict) {

       NSArray *userArray = [dictobjectForKey:@"users"];

       for (NSDictionary *dictin userArray) {

           UserItem *item = [[UserItemalloc] init];

            item.username = [dictobjectForKey:@"username"];

            item.realname = [dictobjectForKey:@"realname"];

            item.uid = [dictobjectForKey:@"uid"];

            item.headimage = [NSStringstringWithFormat:@"http://192.168.88.8/sns%@",[dictobjectForKey:@"headimage"]];

            [dataArrayaddObject:item];

            [itemrelease];

        }

    }

    [mTableViewreloadData];

}


#pragma mark - UITableViewDatasource协议中的方法


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

{

    return [dataArraycount];

}


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

{

    NSString *cellID = @"myCell";

    

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {

        cell = [[[UITableViewCellalloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:cellID]autorelease];

    }

    

    UserItem *item = [dataArrayobjectAtIndex:indexPath.row];

    

    cell.textLabel.text = item.username;

    return cell;

}


@end



原创粉丝点击