ios异步下载加载图片

首先要导入第三方库文件和系统库文件:

有ASIHTTPRequest 和 External

QuartzCore.framework

libz.dylib

libxml2.lib

CFNetwork.framework

MobileCoreServices.framework

SystemConfiguration.framework

EGORefreshTableHeaderView类


IconDownload.h文件:

#import <Foundation/Foundation.h>
@class UserItem;

@interface IconDownload : NSObject
{
    //系统http协议请求类
    NSURLConnection * httpConnection;
    //保存下载的数据
    NSMutableData * downloadData;
}

//保存要下载的图片相关的信息模型对象
@property (nonatomic, retain) UserItem * item;
//下载完成的回调对象
@property (nonatomic, assign) id delegate;
//回调方法
@property (nonatomic, assign) SEL method;
//要下载图片所在的行
@property (nonatomic, retain) NSIndexPath * indexPath;

//开始下载图片
-(void)downloadImage;
//获得指定文件在沙盒目录下的全路径
+(NSString *)filePath:(NSString *)fileName;

@end


IconDownload.m文件

#import "IconDownload.h"
#import "UserItem.h"
#import "NSString+Hashing.h"

@implementation IconDownload

@synthesize item = _item;
@synthesize delegate = _delegate;
@synthesize method = _method;
@synthesize indexPath = _indexPath;

-(void)dealloc
{
    if(httpConnection){
        //        [httpConnection cancel];
        [httpConnection release];
        httpConnection = nil;
    }
    if(downloadData){
        [downloadData release];
        downloadData = nil;
    }
    
    [super dealloc];
}

+(NSString *)filePath:(NSString *)fileName
{
    //获得当前程序的沙盒目录(安装目录)
    NSString * homePath = NSHomeDirectory();
    //我们指定的保存位置
    homePath = [homePath stringByAppendingPathComponent:@"Library/Caches"];
    NSFileManager * fm = [NSFileManager defaultManager];
    //如果指定目录存在
    if([fm fileExistsAtPath:homePath]){
        //要保存的文件名合法
        if(fileName && [fileName length] != 0){
            homePath = [homePath stringByAppendingPathComponent:fileName];
        }
    }else{
        NSLog(@"指定的沙盒目录不存在");
    }
    return homePath;
}

-(void)downloadImage
{
    NSURL * url = [NSURL URLWithString:[self.item.headimage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    httpConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(!downloadData){
        downloadData = [[NSMutableData alloc] initWithCapacity:0];
    }else{
        [downloadData setLength:0];
        self.delegate = nil;
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [downloadData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString * fileName = [self.item.headimage MD5Hash];
    NSString * filePath = [IconDownload filePath:fileName];
    //保存文件
    [downloadData writeToFile:filePath atomically:YES];
    //通知下载完成
    if([self.delegate respondsToSelector:self.method]){
        [self.delegate performSelector:self.method withObject:self];
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"图片下载失败:%@", self.item.headimage);
}


@end

UserItem.h

#import <Foundation/Foundation.h>

@interface UserItem : NSObject
@property (nonatomic, copy) NSString * username;//登录名
@property (nonatomic, copy) NSString * realname;//真名
@property (nonatomic, copy) NSString * headimage;//头像地址
@property (nonatomic, copy) NSString * uid; //用户id
@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSString * qq;//qq号
@property (nonatomic, copy) NSString * birthprovince; //出生省份

@end

UserItem.m

#import "UserItem.h"

@implementation UserItem
@synthesize username = _username;
@synthesize headimage = _headimage;
@synthesize realname = _realname;
@synthesize uid = _uid;
@synthesize name = _name;
@synthesize qq = _qq;
@synthesize birthprovince = _birthprovince;

-(void)dealloc
{
    self.username = nil;
    self.headimage = nil;
    self.realname = nil;
    self.uid = nil;
    self.name = nil;
    self.qq = nil;
    self.birthprovince = nil;
    [super dealloc];
}

@end

UserListViewController.h

#import <UIKit/UIKit.h>
#import "QFHttpDownloadDelegate.h"
#import "EGORefreshTableHeaderView.h"
@class QFHttpDownload;

@interface UserListViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, QFHttpDownloadDelegate, EGORefreshTableHeaderDelegate>
{
    //显示用户信息的表格视图
    UITableView * userTableView;
    //保存用户信息的数组
    NSMutableArray * userArray;
    
    NSInteger curPage;//当前页码
    NSInteger pageCount; //总页数
    NSInteger perPageCount;//每页的数据条数
    BOOL isLoading; //是否正在请求数据
    
//    NSArray * curPageArray;//当前页码的数据
    
    QFHttpDownload * httpDownload;
    
    //下拉刷新视图
    EGORefreshTableHeaderView * refreshView;
    
    //用来保存正在下载中的图片对象(IconDownload)
    NSMutableDictionary * taskDict;

}


@property (nonatomic, retain) NSMutableArray * curPageArray;//当前页码的数据

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


@end

UserListViewController.m


#import "UserListViewController.h"
#import "UserCell.h"
#import "UserItem.h"
#import "UIImageView+WebCache.h"
#import "QFHttpDownload.h"
#import "NSString+Hashing.h"
#import "IconDownload.h"

@interface UserListViewController ()

@end

@implementation UserListViewController

@synthesize curPageArray = _curPageArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIBarButtonItem * leftitem = [[UIBarButtonItem alloc] initWithTitle:@"前一页" style:UIBarButtonItemStyleDone target:self action:@selector(perClicked:)];
        self.navigationItem.leftBarButtonItem = leftitem;
        [leftitem release];
        
        UIBarButtonItem * rightitem = [[UIBarButtonItem alloc] initWithTitle:@"后一页" style:UIBarButtonItemStyleDone target:self action:@selector(nextClicked:)];
        self.navigationItem.rightBarButtonItem = rightitem;
        [rightitem release];
    }
    return self;
}

-(void)perClicked:(UIBarButtonItem *)item
{
    if(isLoading){
        return;
    }
    if([item.title isEqualToString:@"首页"]){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    curPage--;
    if(curPage < 1){
        curPage = 1;
        [item setTitle:@"首页"];
    }
    [self loadData:curPage count:perPageCount];
}

-(void)nextClicked:(UIBarButtonItem *)item
{
    if(isLoading){
        return;
    }
    curPage++;
    if(curPage > pageCount){
        curPage = pageCount;
    }
    [self loadData:curPage count:perPageCount];
}

//加载指定页码的数据,count条
-(void)loadData:(NSInteger)page count:(NSInteger)count
{
    if((curPage - 1) * perPageCount < [userArray count]){
        NSInteger len = perPageCount;
        if(curPage * perPageCount > [userArray count]){
            len = [userArray count] - (curPage - 1) * perPageCount;
        }
        NSRange range = NSMakeRange((curPage - 1) * perPageCount, len);
//        self.curPageArray = [userArray subarrayWithRange:range];
        if(self.curPageArray){//
            [self.curPageArray removeAllObjects];
        }else{
            self.curPageArray = [NSMutableArray arrayWithCapacity:0];
        }
        [self.curPageArray addObjectsFromArray:[userArray subarrayWithRange:range]];//
        [userTableView reloadData];
    }else{
        if(httpDownload){
            isLoading = YES;
            NSString * url = [NSString stringWithFormat:@"http://192.168.88.8/sns/my/user_list.php?page=%d&number=%d", page, count];
            [httpDownload downloadFromUrl:url];
        }else{
            NSLog(@"下载对象为空");
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    userArray = [[NSMutableArray alloc] init];
    
    taskDict = [[NSMutableDictionary alloc] initWithCapacity:0];
    CGRect frame = [[UIScreen mainScreen] bounds];
    frame.size.height -= 64;
    
    userTableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    userTableView.delegate = self;
    userTableView.dataSource = self;
    [self.view addSubview:userTableView];
    
    curPage = 1;
    perPageCount = 20;
    pageCount = 888888;
    
    frame = userTableView.frame;
    frame.origin.y -= frame.size.height;
    refreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:frame];
    refreshView.delegate = self;
    [userTableView addSubview:refreshView];
    //最后刷新时间
    [refreshView refreshLastUpdatedDate];

    
    //实例化下载类对象
    httpDownload = [[QFHttpDownload alloc] init];
    httpDownload.delegate = self;
    //    [httpDownload downloadFromUrl:@"http://192.168.88.8/sns/my/user_list.php"];
    [self loadData:curPage count:perPageCount];
}

//滚动视图发生滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [refreshView egoRefreshScrollViewDidScroll:scrollView];
}

-(void)loadIconOnScreen
{
    //获得当前屏幕可见行的实例
//    NSArray * array = [userTableView visibleCells];
    //获得当前屏幕可见行的索引
    NSArray * array = [userTableView indexPathsForVisibleRows];
    for(NSIndexPath * indexPath in array){
        NSString * filePath = [self fileExists:indexPath];
        if(filePath){
            //加载本地文件
            UserCell * cell = (UserCell *)[userTableView cellForRowAtIndexPath:indexPath];
            cell.headImageView.image = [UIImage imageWithContentsOfFile:filePath];
        }else{
            if(!userTableView.isDecelerating && !userTableView.isDragging){
                [self downloadIcon:indexPath];
            }
        }
    }
}

//停止拖拽
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [refreshView egoRefreshScrollViewDidEndDragging:scrollView];
    [self loadIconOnScreen];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadIconOnScreen];
}

//当前是否正在刷新
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
    return isLoading;
}

//最后刷新时间
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
    return [NSDate date];
}

//在此方法中重新加载数据(触发了刷新)
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
    [self nextClicked:nil];
}

-(void)downloadComplete:(QFHttpDownload *)hd
{
    //用系统的json解析器解析下载结果为json对象
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:hd.downloadData options:NSJSONReadingMutableContainers error:nil];
    
    //计算总页码
    NSString * countstr = [dict objectForKey:@"totalcount"];
    pageCount = [countstr integerValue] % perPageCount == 0 ? [countstr integerValue] / perPageCount : [countstr integerValue] / perPageCount + 1;
    
    if(pageCount == 0){
        pageCount = 88888;
    }
    self.curPageArray = [NSMutableArray arrayWithCapacity:0];
    
    NSArray * array = [dict objectForKey:@"users"];
    for(NSDictionary * subDict in array){
        UserItem * item = [[[UserItem alloc] init] autorelease];
        item.username = [subDict objectForKey:@"username"];
        item.uid = [subDict objectForKey:@"uid"];
        item.realname = [subDict objectForKey:@"realname"];
        item.headimage = [NSString stringWithFormat:@"http://192.168.88.8/sns%@", [subDict objectForKey:@"headimage"]];
//        [userArray addObject:item];
        [self.curPageArray addObject:item];
    }
    isLoading = NO;
    //将数组self.curPageArray的所有元素加入到数组userArray中
    [userArray addObjectsFromArray:self.curPageArray];
    [userTableView reloadData];
    //    [userTableView reloadData];
//    [self loadData:curPage count:pageCount];
    //通知下拉刷新视图结束
    [refreshView egoRefreshScrollViewDataSourceDidFinishedLoading:userTableView];
    isLoading = NO;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.curPageArray count];
}

//检查指定的图片是否存在
-(NSString *)fileExists:(NSIndexPath *)indexPath
{
    UserItem * item = [self.curPageArray objectAtIndex:indexPath.row];
    NSString * fileName = [item.headimage MD5Hash];
    NSString * filePath = [IconDownload filePath:fileName];
    NSFileManager * fm = [NSFileManager defaultManager];
    if([fm fileExistsAtPath:filePath]){
        return filePath;
    }
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * userCellName = @"UserCell";
    UserCell * cell = [tableView dequeueReusableCellWithIdentifier:userCellName];
    if(nil == cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserCell" owner:self options:nil] lastObject];
    }
    UserItem * item = [self.curPageArray objectAtIndex:indexPath.row];
    cell.userNameLabel.text = item.username;
    cell.realNameLabel.text = item.realname;
    cell.uidLabel.text = item.uid;
    cell.headImageView.image = [UIImage imageNamed:@"logo"];
    NSString * filePath = [self fileExists:indexPath];
    if(filePath){
        //加载本地文件
        cell.headImageView.image = [UIImage imageWithContentsOfFile:filePath];
    }else{
        if(!userTableView.isDecelerating && !userTableView.isDragging){
            [self downloadIcon:indexPath];
        }
    }
//    [cell.headImageView setImageWithURL:[NSURL URLWithString:item.headimage]];
    
    return cell;
}

//开始下载指定行的图片
-(void)downloadIcon:(NSIndexPath *)indexPath
{
    UserItem * item = [self.curPageArray objectAtIndex:indexPath.row];
    IconDownload * download = [taskDict objectForKey:item.headimage];
    if(!download){
        download = [[[IconDownload alloc] init] autorelease];
        download.item = item;
        download.delegate = self;
        download.method = @selector(iconDownloadFinished:);
        download.indexPath = indexPath;
        [download downloadImage];
        //保存下载对象
        [taskDict setObject:download forKey:item.headimage];
    }else{
        NSLog(@"图片正在下载中");
    }
}

-(void)iconDownloadFinished:(IconDownload *)download
{
    NSString * filePath = [self fileExists:download.indexPath];
    if(filePath){
        //加载本地文件
        UserCell * cell = (UserCell *)[userTableView cellForRowAtIndexPath:download.indexPath];
        cell.headImageView.image = [UIImage imageWithContentsOfFile:filePath];
    }
    //删除下载对象
    [taskDict removeObjectForKey:download.item.headimage];
    download.delegate = nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0f;
}

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

@end

QFHttpDownloadDelegate.h


#import <Foundation/Foundation.h>
@class QFHttpDownload;

@protocol QFHttpDownloadDelegate <NSObject>

//下载完成协议方法
-(void)downloadComplete:(QFHttpDownload *)hd;
@optional
//下载失败协议方法
-(void)downloadError:(QFHttpDownload *)hd;

@end

QFHttpDownload.h

#import <Foundation/Foundation.h>
//#import "RootViewController.h"
#import "QFHttpDownloadDelegate.h"
#import "ASIHTTPRequest.h"

@interface QFHttpDownload:NSObject <NSURLConnectionDataDelegate>
{
    //系统http协议请求类
    NSURLConnection * httpConnection;
    //下载的二进制数据
    NSMutableData * downloadData;
}

//@property (nonatomic, assign) RootViewController * rvc;
@property (nonatomic, assign) id<QFHttpDownloadDelegate> delegate;
@property (nonatomic, retain) NSMutableData * downloadData;
@property (nonatomic, assign) NSInteger apiType;//请求的类型

//用系统同类进行http请求
-(void)downloadFromUrl:(NSString *)url;
//用第三方库ASIHttpRequest进行http请求
-(void)downloadFromUrlWithASI:(NSString *)url;
//用第三方库ASIHttpRequest进行post请求
-(void)downloadFromUrlWithASI:(NSString *)url dict:(NSDictionary *)dict;

@end

QFHttpDownload.m

#import "QFHttpDownload.h"
//第三方post请求类头文件
#import "ASIFormDataRequest.h"

@implementation QFHttpDownload

@synthesize downloadData;
@synthesize apiType = _apiType;
@synthesize delegate = _delegate;

-(void)dealloc
{
    [downloadData release];
    downloadData = nil;
    [httpConnection cancel];
    [httpConnection release];
    httpConnection=nil;
    [super dealloc];
}

-(id)init
{
    if(self = [super init]){
        //实例化缓冲区
        downloadData = [[NSMutableData alloc] initWithCapacity:0];
    }
    return self;
}

//第三方http请求
-(void)downloadFromUrlWithASI:(NSString *)url
{
    NSURL * newUrl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //创建asi请求对象
    ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:newUrl];
    //设置回调(代理)
    request.delegate = self;
    //启动异步(下载)请求
    [request startAsynchronous];
}

//第三方post请求
-(void)downloadFromUrlWithASI:(NSString *)url dict:(NSDictionary *)dict
{
    NSURL * newUrl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL:newUrl];
    for(NSString * key in [dict allKeys]){
        NSObject * object = [dict objectForKey:key];
        //如果参数值为二进制数据,则相当于上传文件
        if([object isKindOfClass:[NSData class]]){
            [request setData:object withFileName:@"temp.png" andContentType:@"image/png" forKey:key];
        }else{
            //设置post请求参数
            [request setPostValue:object forKey:key];
        }
    }
    
    request.delegate = self;
    [request startAsynchronous];
}

//第三方下载完成协议方法
-(void)requestFinished:(ASIHTTPRequest *)request
{
    //清空旧数据
    [downloadData setLength:0];
    //保存新数据
    [downloadData appendData:[request responseData]];
    //检查对象self.delegate是否有方法downloadComplete
    if([self.delegate respondsToSelector:@selector(downloadComplete:)]){
        [self.delegate downloadComplete:self];
    }
    
}

//第三方下载失败协议方法
-(void)requestFailed:(ASIHTTPRequest *)request
{
    //清空旧数据
    [downloadData setLength:0];
    //检查对象self.delegate是否有方法downloadError
    if([self.delegate respondsToSelector:@selector(downloadError:)]){
        [self.delegate downloadError:self];
    }
    
}

//从指定的网址请求数据
-(void)downloadFromUrl:(NSString *)url
{
    //实例化缓冲区
    downloadData = [[NSMutableData alloc] initWithCapacity:0];
    //用服务器地址字符串构造NSURL对象
    NSURL * newUrl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //构造请求类对象
    NSURLRequest * request = [NSURLRequest requestWithURL:newUrl];
    //创建连接类对象,此方式异步方法,一旦对象创建,就开始了数据下载,通过协议方法回调
    httpConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

//收到服务器的响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //打印状态码
    //    response isMemberOfClass:]
    if([response isKindOfClass:[NSHTTPURLResponse class]]){
        NSHTTPURLResponse * newResponse = (NSHTTPURLResponse *)response;
        NSLog(@"状态码:%d", [newResponse statusCode]);
    }
    //收到新回应清空旧数据
    [downloadData setLength:0];
}

//开始接收数据,此方法多次调用
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //将每次接收的数据保存
    [downloadData appendData:data];
}

//数据下载完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //检查对象self.delegate是否有方法downloadComplete
    if([self.delegate respondsToSelector:@selector(downloadComplete:)]){
        [self.delegate downloadComplete:self];
    }
}

//请求失败的协议方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"请求失败");
    //检查对象self.delegate是否有方法downloadError
    if([self.delegate respondsToSelector:@selector(downloadError:)]){
        [self.delegate downloadError:self];
    }
}


@end


LoginViewController.h


#import <UIKit/UIKit.h>
#import "QFHttpDownloadDelegate.h"
@class QFHttpDownload;

@interface LoginViewController : UIViewController <UITextFieldDelegate, QFHttpDownloadDelegate>
{
    QFHttpDownload * httpDownload;
}

@end




#import "LoginViewController.h"
#import "AppDelegate.h"
#import "QFHttpDownload.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(UILabel *)CreateLabel:(CGRect)frame name:(NSString *)name
{
    UILabel * label = [[UILabel alloc] initWithFrame:frame];
    label.text = name;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:18];
    return [label autorelease];
}

//创建输入框控件
-(UITextField *)createTextField:(CGRect)frame name:(NSString *)placeHolder tag:(NSInteger)tag
{
    UITextField * textFiled = [[UITextField alloc] initWithFrame:frame];
    textFiled.borderStyle = UITextBorderStyleRoundedRect;
    textFiled.placeholder = placeHolder;
    textFiled.tag = tag;
    textFiled.delegate = self;
    return [textFiled autorelease];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//让视图view上得所有可能是第一响应者的对象放弃第一响应(收键盘)
//这个示例中是所有的UITextField对象
-(void)resignAllFirstResponder:(UIView *)view
{
    for(UIView * subView in view.subviews){
        if([subView isKindOfClass:[UITextField class]]){
            [subView resignFirstResponder];
        }else{
            [self resignAllFirstResponder:subView];
        }
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self resignAllFirstResponder:self.view];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor purpleColor];
    NSArray * array = [NSArray arrayWithObjects:@"用户名", @"密码", @"邮箱", nil];
    int i = 0;
    for(NSString * name in array){
        CGRect frame = CGRectMake(10, 10 + i * 40, 60, 30);
        UILabel * label = [self CreateLabel:frame name:name];
        [self.view addSubview:label];
        
        frame = CGRectMake(80, 10 + i * 40, 200, 30);
        UITextField * textField = [self createTextField:frame name:[NSString stringWithFormat:@"请输入%@", name] tag:100 + i];
        if([name isEqualToString:@"密码"]){
            textField.secureTextEntry = YES;
        }
        [self.view addSubview:textField];
        i++;
    }
    NSArray * btnNameArray = [NSArray arrayWithObjects:@"注册", @"登录", nil];
    for(int i = 0; i < 2; i++){
        UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        NSInteger space = (320 - 60 * 2) / (2 + 1);
        button.frame = CGRectMake(space + (space + 60) * i, 150, 60, 30);
        [button setTitle:[btnNameArray objectAtIndex:i] forState:UIControlStateNormal];
        button.tag = 200 + i;
        [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
    //创建http请求类对象
    httpDownload = [[QFHttpDownload alloc] init];
    httpDownload.delegate = self;
    
}

-(void)downloadComplete:(QFHttpDownload *)hd
{
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:hd.downloadData options:NSJSONReadingMutableContainers error:nil];
    if(dict){
        NSLog(@"下载结果:%@", dict);
        if(hd.apiType == LOGIN_TYPE){
            NSString * code = [dict objectForKey:@"code"];
            if([code isEqualToString:@"login_success"]){
                //登录成功保存用户id
                [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"uid"] forKey:@"uid"];
                //保存用户token标识
                [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"m_auth"] forKey:@"m_auth"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [SharedApp showViewController:ROOT_VIEW_CONTROLLER];
            }
            NSLog(@"登录结果:%@", [dict objectForKey:@"message"]);
        }else if(hd.apiType == REGIST_TYPE){
            NSString * code = [dict objectForKey:@"code"];
            if([code isEqualToString:@"registered"]){
                
            }
            NSLog(@"注册结果:%@", [dict objectForKey:@"message"]);
        }
    }
}

-(void)downloadError:(QFHttpDownload *)hd
{
    
}

//获得输入的所有信息(用户名密码邮箱等)
-(NSArray *)allValues
{
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
    for(int i = 100; i < 103; i++){
        UITextField * textField = (UITextField *)[self.view viewWithTag:i];
        if(textField){
            if(textField.text && [textField.text length] != 0){
                [array addObject:textField.text];
            }
        }
    }
    return array;
}

-(void)btnPressed:(UIButton *)button
{
    switch (button.tag) {
        case 200:{
            NSArray * array = [self allValues];
            if([array count] == 3){
                NSString * url = [NSString stringWithFormat:@"%@%@?username=%@&password=%@&email=%@", HOST_URL, REGIST_URL, [array objectAtIndex:0], [array objectAtIndex:1], [array objectAtIndex:2]];
                NSLog(@"url:%@", url);
                //开始注册
                httpDownload.apiType = REGIST_TYPE;
                [httpDownload downloadFromUrl:url];
            }
        }
            break;
        case 201:{
            //演示跳转
//            [SharedApp showViewController:ROOT_VIEW_CONTROLLER];
            NSArray * array = [self allValues];
            if([array count] == 2){
                NSString * url = [NSString stringWithFormat:@"%@%@?username=%@&password=%@", HOST_URL, LOGIN_URL, [array objectAtIndex:0], [array objectAtIndex:1]];
                NSLog(@"url:%@", url);
                //开始注册
                httpDownload.apiType = LOGIN_TYPE;
                [httpDownload downloadFromUrl:url];
            }

        }
            
            break;
        default:
            break;
    }
}

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

@end


LoginViewController.m


//  PhotoListViewController.m


#import "PhotoListViewController.h"
#import "QFHttpDownload.h"
#import "PhotoItem.h"
#import "CustomImageView.h"
#import "PhotoCell.h"
#import "UIImageView+WebCache.h"
#import "DetailViewController.h"

@interface PhotoListViewController ()

@end

@implementation PhotoListViewController
@synthesize picArray = _picArray;

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

-(void)dealloc
{
    self.picArray = nil;
    httpDownload.delegate = nil;
    [httpDownload release];
    [super dealloc];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    _picArray = [[NSMutableArray alloc] initWithCapacity:0];
    //实例化http请求类
    httpDownload = [[QFHttpDownload alloc] init];
    //设置回调
    httpDownload.delegate = self;
    //拼接接口地址
    NSString * url = [NSString stringWithFormat:@"%@%@", HOST_URL, PHOTO_LIST_URL];
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"m_auth"];
    NSString * uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    //构造参数列表
    NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:token, @"m_auth", uid, @"uid", self.aid, @"id", nil];
    //发送请求
    httpDownload.apiType = PHOTO_LIST_TYPER;
    [httpDownload downloadFromUrlWithASI:url dict:dict];
}

-(void)downloadComplete:(QFHttpDownload *)hd
{
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:hd.downloadData options:NSJSONReadingMutableContainers error:nil];
    if(dict){
        if(hd.apiType == PHOTO_UPLOAD_TYPE){
            NSLog(@"上传结果:%@", [dict objectForKey:@"message"]);
            return;
        }
        NSArray * array = [dict objectForKey:@"photos"];
        for(NSDictionary * subDict in array){
            PhotoItem * item = [[[PhotoItem alloc] init] autorelease];
            item.aid = [subDict objectForKey:@"albumid"];
            item.pid = [subDict objectForKey:@"picid"];
            item.uid = [subDict objectForKey:@"uid"];
            item.width = [subDict objectForKey:@"width"];
            item.height = [subDict objectForKey:@"height"];
            item.title = [subDict objectForKey:@"title"];
            item.pic = [NSString stringWithFormat:@"%@/%@", HOST_URL, [subDict objectForKey:@"pic"]];
            [self.picArray addObject:[NSString stringWithFormat:@"%@/%@", HOST_URL, [subDict objectForKey:@"pic"]]];
            [dataArray addObject:item];
        }
        NSLog(@"数据:%d", [dataArray count]);
        NSLog(@"图片:%@,个数:%d", _picArray, [_picArray count]);
        [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
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = [dataArray count] % 4 == 0 ? [dataArray count] / 4 : [dataArray count] / 4 + 1;
    return count;
}

-(void)imageClicked:(CustomImageView *)imageView//城市之光
{
    NSLog(@"clicked:%d", imageView.tag - 100);
//    NSData * data = UIImagePNGRepresentation(imageView.image);
//    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"m_auth"];
//    NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:token, @"m_auth", data, @"attach", self.aid, @"albumid", @"测试", @"pic_title", nil];
//    NSString * url = [NSString stringWithFormat:@"%@%@",HOST_URL,PHOTO_UPLOAD_URL];
//    httpDownload.apiType = PHOTO_UPLOAD_TYPE;
//    [httpDownload downloadFromUrlWithASI:url dict:dict];
    
    DetailViewController * dvc = [[DetailViewController alloc] init];
    dvc.selectIndex = imageView.tag - 100;
    dvc.count = [dataArray count];
    dvc.pArray = self.picArray;
    NSLog(@"%d,%d,%@", dvc.selectIndex, dvc.count, dvc.pArray);

    [self.navigationController pushViewController:dvc animated:YES];
    [dvc release];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    PhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(nil == cell){
        cell=[[[NSBundle mainBundle] loadNibNamed:@"PhotoCell" owner:self options:nil] lastObject];
        NSArray *array=[NSArray arrayWithObjects:cell.photoView1,cell.photoView2,cell.photoView3,cell.photoView4, nil];
        //添加点击事件
        for (CustomImageView *imageView in array) {
            imageView.delegate=self;
            imageView.method=@selector(imageClicked:);
        }
    }
    //设置无行选中效果
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *array=[NSArray arrayWithObjects:cell.photoView1,cell.photoView2,cell.photoView3,cell.photoView4, nil];

    int i = indexPath.row * 4;
    for(CustomImageView * imageView in array){
        imageView.tag = i + 100;
        if(i < [dataArray count]){
            PhotoItem * item = [dataArray objectAtIndex:i];
            imageView.hidden = NO;
            [imageView setImageWithURL:[NSURL URLWithString:item.pic]];
        }else{
            imageView.hidden = YES;
        }
        i++;
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 104.0f;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

@end



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值