#import <Foundation/Foundation.h>
#import "DataManagerProtocol.h"
@interface DataManager : NSObject<NSURLConnectionDataDelegate>
{
//加载网络数据
NSURLConnection *_connection;
//存储网络数据
NSMutableData *_mutData;
}
//开始加载网络数据
-(void)startLoadWebData:(NSString *)strURL;
@property(strong,nonatomic)id<DataManagerProtocol>delegate;
@end
#import "DataManager.h"
@implementation DataManager
-(void)startLoadWebData:(NSString *)strURL
{
_mutData=[[NSMutableData alloc]init];
//初使化网络链接
NSURL *url=[NSURL URLWithString:strURL];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
_connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
#pragma mark NSURLConnectionDataDelegate
//404 域名错误
//500 服务器错误
//200 正常
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//返回服务器状态信息
NSHTTPURLResponse *req=(NSHTTPURLResponse *)response;
NSLog(@"%i",[req statusCode]);
//清空数据
_mutData.length=0;
}
//该方法当时加载大数据时,可能被调用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_mutData appendData:data];
}
//网络数据加载结束时调用该方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//解析网络数据
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:_mutData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
NSArray *array=[dict objectForKey:@"users"];
[self.delegate recvieWebData:array];
}
//实例化业务逻辑
_dataManager =[[DataManager alloc]init];
_dataManager.delegate=self;
//请求后台数据
[_dataManager startLoadWebData:@"http://10.0.8.8/sns/my/user_list.php?page=1&number=5"];
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell=[tableView dequeueReusableCellWithIdentifier:@"strIdentifier"];
//从数据源中获得数据
NSDictionary *dict=[_array objectAtIndex:indexPath.row];
cell.upLabel.text=[dict objectForKey:@"username"];
cell.downLabel.text=[dict objectForKey:@"credit"];
//加载网络图片
NSString *imageURL=[NSString stringWithFormat:@"http://10.0.8.8/sns%@",[dict objectForKey:@"headimage"]];
NSURL *url=[NSURL URLWithString:imageURL];
//将网址对应的图片加载计算机内从
NSData *data=[[NSData alloc]initWithContentsOfURL:url];
UIImage *image=[[UIImage alloc]initWithData:data];
cell.imgView.image=image;
return cell;
}