ownerblood

导航

 

首先必须引入新浪官方的api接口,SinaWeiBoSDK文件夹的所有东西

然后进行key的验证以及接口的调用

 

 

MainViewController.h:

 

//
//  MainViewController.h
//  sinaWeiBo2
//
//  Created by Mac on 6/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "WBEngine.h"
#import "WBSendView.h"
#import "WBLogInAlertView.h"
#import "MainTable.h"

//#import "DemoTableViewController.h"


@interface MainViewController : UIViewController<WBEngineDelegate, UIAlertViewDelegate, WBLogInAlertViewDelegate>
{
    WBEngine *weiBoEngine;
    UIActivityIndicatorView *indicatorView;
    UIButton *logInBtnOAuth;
    
    MainTable *mainTableView;
    //MainTable2 *mainTableView2;
    
    UINavigationController  *navigationController;
    
   
}
@property (nonatomic, retain) WBEngine *weiBoEngine;
@end

 

MainViewController.m

 

//
//  MainViewController.m
//  sinaWeiBo2
//
//  Created by Mac on 6/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController (Private)

- (void)dismissTimelineViewController;
- (void)presentTimelineViewController:(BOOL)animated;
- (void)presentTimelineViewControllerWithoutAnimation;

@end

@implementation MainViewController
@synthesize weiBoEngine;

-(void)loadView
{
    [super loadView];
    
    
    
    
    WBEngine *engine=[[WBEngine alloc] initWithAppKey:key appSecret:pass];
    [engine setRootViewController:self];
    [engine setDelegate:self];
    [engine setIsUserExclusive:NO];
    self.weiBoEngine=engine;
    [engine release];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
//    logInBtnOAuth = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [logInBtnOAuth setFrame:CGRectMake(85, 160, 150, 40)];
//    [logInBtnOAuth setTitle:@"Log In With OAuth" forState:UIControlStateNormal];
//    [logInBtnOAuth addTarget:self action:@selector(onLogInOAuthButtonPressed) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:logInBtnOAuth];
    
    indicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    [indicatorView setCenter:CGPointMake(160, 240)];
    [self.view addSubview:indicatorView];

//    if ([weiBoEngine isLoggedIn]&&![weiBoEngine isAuthorizeExpired]) {
//        [self performSelector:@selector(presentTimelineViewControllerWithoutAnimation) withObject:nil afterDelay:0.0];
//    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self onLogInOAuthButtonPressed];
}

- (void)onLogInOAuthButtonPressed
{
    [weiBoEngine logIn];
}

- (void)presentTimelineViewControllerWithoutAnimation
{
    [self presentTimelineViewController:NO];
}

-(void)engineDidLogIn:(WBEngine *)engine
{
    [indicatorView stopAnimating];
    UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil
                                                    message:@"登录成功!"
                                                    delegate:self
                                                    cancelButtonTitle:@"确定"
                                                    otherButtonTitles:nil];
    
    [alertView setTag:101];
    [alertView show];
    [alertView release];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==101) {
        [self presentTimelineViewController:NO];
    }
}

-(void)presentTimelineViewController:(BOOL)animated
{
    mainTableView=[[MainTable alloc]init];
    navigationController=[[UINavigationController alloc]initWithRootViewController:mainTableView];
    //mainTableView2=[[DemoTableViewController alloc]init];
    //navigationController=[[UINavigationController alloc]initWithRootViewController:mainTableView2];
    navigationController.view.frame=self.view.bounds;
    [self.view addSubview:navigationController.view];
}


@end

 

mainTable.h

 

//
//  MainTable.h
//  sinaWeiBo2
//
//  Created by Mac on 6/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "WBEngine.h"
#import "WBSendView.h"
#import "DownRefresh.h"
#import "tempViewController.h"
#import <sqlite3.h>

#define key @"595401249"
#define pass @"bf376ac25da61ad03105fed80439eeaf"

@interface MainTable : UITableViewController<UITableViewDelegate,UITableViewDataSource,WBEngineDelegate,WBSendViewDelegate,UIScrollViewDelegate>
{
    WBEngine *engine;
    NSMutableArray *timeLine;
    DownRefresh   *_downRefresh;
    UILabel    *_textText;
    UILabel       *_labelname;
    BOOL     *flagShuaxin;
    BOOL     toAddPage;
    int      paging;
    int      counting;
    int      forPaging;
    int      yomei;
    float      cellHeight;
    tempViewController      *_tempViewController;
    sqlite3 *database;
    NSDictionary    *infoDictionary;
    NSMutableDictionary    *tempDictionary;
    NSDictionary    *tempInfoDictionary;
}
@end

 

maintable.m

 

//
//  MainTable.m
//  sinaWeiBo2
//
//  Created by Mac on 6/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MainTable.h"

@interface MainTable (Private)

-(void)refreshTimeline;

@end

@implementation MainTable



- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        _tempViewController=[[tempViewController alloc]init];
        [_tempViewController VersionNumber];
        
        NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSLog(@"Get document path:%@",[documentsPaths objectAtIndex:0]);
        
        NSString *databaseFilePath=[[documentsPaths objectAtIndex:0]stringByAppendingPathComponent:@"SinaWeiBo"];
        
        if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) {
            NSLog(@"链接成功");
        }else {
            NSLog(@"链接失败");
        }
        
        char *errorMsg;
        
        const char *creatSql="create table if not exists MainInfo(id integer primary key autoincrement,name text,headerUrl text,texting text)";
        
        if (sqlite3_exec(database, creatSql, NULL, NULL, &errorMsg)==SQLITE_OK) {
            NSLog(@"创建成功");
        }else {
            NSLog(@"error: %s",errorMsg);
            sqlite3_free(errorMsg);
        }
        
        const char *insertSql="insert into MainInfo(id,texting) values (1,'刷新')";
        
        if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK) {
            NSLog(@"执行语句成功");
        }else {
            NSLog(@"error: %s",errorMsg);
            sqlite3_free(errorMsg);
        }
        
        
        sqlite3_close(database);
        
        engine=[[WBEngine alloc] initWithAppKey:key appSecret:pass];
        [engine setDelegate:self];
        
        timeLine=[[NSMutableArray alloc]init];
        
        toAddPage=NO;
        paging=1;
        counting=2;
        forPaging=0;
        yomei=0;//0代表no
                
        _downRefresh=[[DownRefresh alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
        
        [self.tableView addSubview:_downRefresh];
        [_downRefresh release];
        
        //[self.tableView insertSubview:downRefresh atIndex:0];
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    [self refreshTimeline];
}

- (void)refreshTimeline
{
//    NSMutableDictionary  *params=[NSMutableDictionary dictionaryWithCapacity:1];
//    [params setObject:[NSString stringWithFormat:@"%d", 1] forKey:@"count"];
//    [params setObject:[NSString stringWithFormat:@"%d", 1] forKey:@"page"];
    [engine loadRequestWithMethodName:@"statuses/home_timeline.json"
                           httpMethod:@"GET"
                               params:nil
                         postDataType:kWBRequestPostDataTypeNone
                     httpHeaderFields:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"timeLine count=%d",[timeLine count]);
    return [timeLine count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //去掉缓存判断,零时方案
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Timeline Cell"];
    
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Timeline Cell"] autorelease];
        
        
    infoDictionary=[NSDictionary alloc];
    
    
    NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *databaseFilePath=[[documentsPaths objectAtIndex:0]stringByAppendingPathComponent:@"SinaWeiBo"];
    
    if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) {
        NSLog(@"链接成功");
    }else {
        NSLog(@"链接失败");
    }
    
    if (tempDictionary!=nil) {      //判断是否是第一行
        int rv;
        sqlite3_stmt *stmt;
        NSString *cellRow;
        char szSql[128]={0};
        char cellRowing[128]={0};
        // NSString *urlstring;
        NSString *namestring;
        NSString *textstring;
        NSString *rowCont;
        
        strcpy(szSql, "select name,headerUrl,texting from MainInfo where id=?");
        
        rv=sqlite3_prepare(database, szSql, 128, &stmt, NULL);
        
        if (rv!=SQLITE_OK) {
            fprintf(stderr,"sqlite3_prepare(%d): %s\n", rv, sqlite3_errmsg(database));
        }
        
        int row=[indexPath indexAtPosition:1];
        
        cellRow=[NSString stringWithFormat:@"%d",row];
        
        strcpy(cellRowing,(char *)[cellRow UTF8String]);
        
        
        rv=sqlite3_bind_text(stmt, 1, cellRowing, strlen(cellRowing), SQLITE_STATIC);
        
        if (rv!=SQLITE_OK) {
            fprintf(stderr,"sqlite3_bind_text(%d): %s\n", rv, sqlite3_errmsg(database));   
        }
        
        rv=sqlite3_step(stmt);
        if ((rv!=SQLITE_OK)&&(rv != SQLITE_DONE)&&(rv != SQLITE_ROW)) {
            fprintf(stderr,"sqlite3_step(%d): %s\n", rv, sqlite3_errmsg(database));
        }
        
        while( rv == SQLITE_ROW ){
            //tempDictionary=[NSMutableDictionary dictionaryWithObjectAndKeys:row,];
            
            //tempInfoDictionary=[NSDictionary dictionaryWithObject:@"namestring" forKey:@"name"];
            
            
            fprintf(stderr,"返回结果为: %s\n", sqlite3_column_text(stmt,0));
            
            _labelname=[[UILabel alloc]init];
            
            //NSString *namestring=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(stmt,0) encoding:NSUTF8StringEncoding];
            
            if ([[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 0) encoding:NSUTF8StringEncoding]!=nil) {
                namestring=[[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 0) encoding:NSUTF8StringEncoding];
            }
            
            _labelname.text=namestring;
            _labelname.frame=CGRectMake(70, 10, 150, 30);
            _labelname.font=[UIFont fontWithName:@"Helvetica-Bold" size:20.0];
            [cell addSubview:_labelname];
            [_labelname release];
            
            
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%s",sqlite3_column_text(stmt,1)]];
            //NSLog(@"%@",url);
            UIImage *imageHeader=[[UIImage alloc]initWithData:[NSData dataWithContentsOfURL: url]];//图片
            UIImageView *imageView=[[UIImageView alloc]initWithImage:imageHeader];
            imageView.frame=CGRectMake(10, 10, 50, 50);
            [cell addSubview:imageView];
            [imageView release];
            
            
            if ([[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 2) encoding:NSUTF8StringEncoding]!=nil) {
                textstring=[[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 2) encoding:NSUTF8StringEncoding];
            }
            
            
            
            NSString *desc=textstring;
            CGSize size=[desc sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(240, 200) lineBreakMode:UILineBreakModeWordWrap];//label分行
            
            _textText=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, cell.frame.size.width-40, 10+size.height+10)];
            _textText.text=textstring;
            _textText.numberOfLines=0;//设置最多多少行
            
            [cell addSubview:_textText];
            [_textText release];
            
            tempInfoDictionary=[NSDictionary dictionaryWithObjectsAndKeys:namestring,@"name",sqlite3_column_text(stmt,1),@"userURL",textstring,@"text", nil];
            //将数据添加进字典中
            //[tempDictionary setObject:@"张三" forKey:@"name1"];
            
            rowCont=[NSString stringWithFormat:@"%d",row];
            /***************小于3判断*******************/
            if (row<3) {
                tempDictionary=[NSMutableDictionary dictionaryWithObjectsAndKeys:rowCont,@"key",tempInfoDictionary,@"info", nil];
                
                [tempDictionary setObject:@"张三" forKey:@"name1"];
                
                [namestring release];
                [textstring release];
                [rowCont release];
                [tempInfoDictionary release];
                rv = sqlite3_step(stmt);
            }else {
                [namestring release];
                [textstring release];
                [rowCont release];
                [tempInfoDictionary release];
                /***********重新定向查询+3数据***************/
                rv = sqlite3_step(stmt);
                
                strcpy(szSql, "select name,headerUrl,texting from MainInfo where id=?");
                
                rv=sqlite3_prepare(database, szSql, 128, &stmt, NULL);
                
                if (rv!=SQLITE_OK) {
                    fprintf(stderr,"sqlite3_prepare(%d): %s\n", rv, sqlite3_errmsg(database));
                }
                
                int row=[indexPath indexAtPosition:1];
                
                for (int i=1; i<=3; i++) {
                    cellRow=[NSString stringWithFormat:@"%d",row+i];
                    
                    strcpy(cellRowing,(char *)[cellRow UTF8String]);
                    
                    
                    rv=sqlite3_bind_text(stmt, 1, cellRowing, strlen(cellRowing), SQLITE_STATIC);
                    
                    if (rv!=SQLITE_OK) {
                        fprintf(stderr,"sqlite3_bind_text(%d): %s\n", rv, sqlite3_errmsg(database));   
                    }
                    
                    rv=sqlite3_step(stmt);
                    if ((rv!=SQLITE_OK)&&(rv != SQLITE_DONE)&&(rv != SQLITE_ROW)) {
                        fprintf(stderr,"sqlite3_step(%d): %s\n", rv, sqlite3_errmsg(database));
                    }
                    
                    while( rv == SQLITE_ROW ){
                        if ([[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 0) encoding:NSUTF8StringEncoding]!=nil) {
                            namestring=[[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 0) encoding:NSUTF8StringEncoding];
                        }
                        
                        if ([[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 2) encoding:NSUTF8StringEncoding]!=nil) {
                            textstring=[[NSString alloc]initWithCString:(char *)sqlite3_column_text(stmt, 2) encoding:NSUTF8StringEncoding];
                        }
                        
                        //tempInfoDictionary=[NSDictionary dictionaryWithObjectsAndKeys:namestring,@"name",sqlite3_column_text(stmt,1),@"userURL",textstring,@"text", nil];
                    }
                }
                
                
                /*********************************************/
            }
            
            
            
        }
        
        
        rv = sqlite3_finalize(stmt);
        if( rv != SQLITE_OK ){
            fprintf(stderr,"sqlite3_finalize(%d): %s\n", rv, sqlite3_errmsg(database));
        }
        
        
        sqlite3_close(database);
    }
    else {      //当不为第一行时将数据存入数组并将num+3的数据一起存入
        
        //tempDictionary=[NSMutableDictionary dictionaryWithObjectAndKeys:@""];
    }
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectAndKeys:@"just",@"firstname",   
//                          @"code",@"lastname",  
//                          @"xcode@apple.com",@"email",  
//                          nil];   
    
    
    
    
    
    
    
    
    
    
        
        
        
//        NSDictionary *detail = [timeLine objectAtIndex:indexPath.row];
//        
//        //cell.imageView.image=[UIImage imageNamed:@"bili"];
//        NSURL *url=[NSURL URLWithString:[[detail objectForKey:@"user"]objectForKey:@"profile_image_url"]];
//        //NSLog(@"%@",url);
//        UIImage *imageHeader=[[UIImage alloc]initWithData:[NSData dataWithContentsOfURL: url]];//图片
//        UIImageView *imageView=[[UIImageView alloc]initWithImage:imageHeader];
//        imageView.frame=CGRectMake(10, 10, 50, 50);
//        [cell addSubview:imageView];
//        [imageView release];
//        //cell.imageView.image=imageHeader;
//        
//        _labelname=[[UILabel alloc]init];
//        _labelname.text=[[detail objectForKey:@"user"] objectForKey:@"screen_name"];
//        _labelname.frame=CGRectMake(70, 10, 150, 30);
//        _labelname.font=[UIFont fontWithName:@"Helvetica-Bold" size:20.0];
//        [cell addSubview:_labelname];
//        [_labelname release];
//        //[cell.detailTextLabel setText:[detail objectForKey:@"text"]];
//        // Configure the cell...
//        
//        //    _labelText=[[UILabel alloc]init];
//        //    _labelText.text=[detail objectForKey:@"text"];
//        //    _labelText.frame=CGRectMake(10, 60, 200, 20);
//        //    _labelText.font=[UIFont fontWithName:@"Arial" size:12.0];
//        //   // _labelText.backgroundColor=[UIColor redColor];
//        //    [cell addSubview:_labelText];
//        
//        NSString *desc=[detail objectForKey:@"text"];
//        CGSize size=[desc sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(240, 200) lineBreakMode:UILineBreakModeWordWrap];//label分行
//        
//        _textText=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, cell.frame.size.width-40, 10+size.height+10)];
//        _textText.text=[detail objectForKey:@"text"];
//        _textText.numberOfLines=0;//设置最多多少行
//        //_textText.frame=CGRectMake(10, 60, cell.frame.size.width-40, 50);
//        //_textText.font=[UIFont fontWithName:@"Arial" size:12.0];
//        
//        [cell addSubview:_textText];
//        [_textText release];
    
    return cell;
}

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *detail = [timeLine objectAtIndex:indexPath.row];
    NSString *desc=[detail objectForKey:@"text"];
    CGSize size=[desc sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(240, 200) lineBreakMode:UILineBreakModeWordWrap];//label分行
    NSLog(@"高度是%f",size.height);
    return 130.0+10.0+size.height+10.0;
}

-(void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
{
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict=(NSDictionary *)result;
        [timeLine addObjectsFromArray:[dict objectForKey:@"statuses"]];
        [self.tableView reloadData];
    }
    
     NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *databaseFilePath=[[documentsPaths objectAtIndex:0]stringByAppendingPathComponent:@"SinaWeiBo"];
    
    if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) {
        NSLog(@"链接成功");
    }else {
        NSLog(@"链接失败");
    }
    
    
    
    NSDictionary *detail;
   // NSLog(@"数量为%@",timeLine.count);
    
    int rv;
    sqlite3_stmt *stmt;
    char szSql[128]={ 0 };
    char headerUrl[128]={0};
    char nameing[128]={0};
    char texting[512]={0};
    NSString *urlstring;
    NSString *namestring;
    NSString *textstring;
    
    strcpy(szSql,"insert into MainInfo(headerUrl,name,texting) values (?,?,?)");
    
    
    for (int i=0; i<timeLine.count; i++) {
        
        NSLog(@"当前计数+%d",i);
        
        detail = [timeLine objectAtIndex:i];
        
        rv = sqlite3_prepare(database, szSql, 128,&stmt,NULL);
        if( rv != SQLITE_OK ){
            fprintf(stderr,"sqlite3_prepare(%d): %s\n", rv, sqlite3_errmsg(database));
        }
        
        urlstring=[[detail objectForKey:@"user"]objectForKey:@"profile_image_url"];
        
        strcpy(headerUrl,(char *)[urlstring UTF8String]);
        
        namestring=[[detail objectForKey:@"user"] objectForKey:@"screen_name"];
        
        strcpy(nameing,(char *)[namestring UTF8String]);
        
        textstring=[detail objectForKey:@"text"];
        
        strcpy(texting,(char *)[textstring UTF8String]);

        rv = sqlite3_bind_text(stmt, 1, headerUrl,strlen(headerUrl), SQLITE_STATIC);
        rv = sqlite3_bind_text(stmt, 2, nameing,strlen(nameing), SQLITE_STATIC);
        rv = sqlite3_bind_text(stmt, 3, texting,strlen(texting), SQLITE_STATIC);
        
        
        if( rv != SQLITE_OK ){
            fprintf(stderr,"sqlite3_bind_text(%d): %s\n", rv, sqlite3_errmsg(database));
        }
        
        rv = sqlite3_step(stmt);
        if((rv != SQLITE_OK)&&(rv != SQLITE_DONE)&&(rv != SQLITE_ROW)){
            fprintf(stderr,"sqlite3_step(%d): %s\n", rv, sqlite3_errmsg(database));
        }
        
        
//        while( rv == SQLITE_ROW ){
//            //fprintf(stderr,"返回结果为: %s\n", sqlite3_column_text(stmt,0));
//            rv = sqlite3_step(stmt);
//        }
        
        rv = sqlite3_finalize(stmt);
        if( rv != SQLITE_OK ){
            fprintf(stderr,"sqlite3_finalize(%d): %s\n", rv, sqlite3_errmsg(database));
        }
                
        
    }
    

    sqlite3_close(database);
    
    [timeLine release];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.tableView.contentOffset.y<-150)
    {
        paging=1;
        counting=2;
        toAddPage=NO;
        yomei=0;
        //[self refreshTimeline];
        //[self engine:engine requestDidSucceedWithResult:self];
        //[self.tableView reloadData];
        
        
        self.view.userInteractionEnabled = NO;
        [engine release];
        
        engine=[[WBEngine alloc] initWithAppKey:key appSecret:pass];
        [engine setDelegate:self];
        timeLine=nil;
        //[timeLine release];
        timeLine=[[NSMutableArray alloc]init];
        [self refreshTimeline];
        [self engine:engine requestDidSucceedWithResult:self];
        //[self.tableView reloadData];
        [self.tableView reloadData];
        
        self.view.userInteractionEnabled = YES;
        //NSLog(@"123");
        /*[self refreshTimeline];
        [self.tableView reloadData];
        [self.tableView reloadInputViews];
        */
        //[self init];
    }
//    }else if (self.tableView.contentOffset.y>460*paging) {
//        self.view.userInteractionEnabled = NO;
//        if (yomei==0) {
//            paging+=2;
//        }
//        
//        
//        NSLog(@"长度是%f",self.view.frame.size.height*paging);
//        
//        engine=[[WBEngine alloc] initWithAppKey:key appSecret:pass];
//        [engine setDelegate:self];
//        timeLine=nil;
//        timeLine=[[NSMutableArray alloc]init];
//        NSMutableDictionary  *params=[NSMutableDictionary dictionaryWithCapacity:1];
//        
//        
//        [params setObject:[NSString stringWithFormat:@"%d", 20*counting] forKey:@"count"];
//
//        
//        forPaging=20*counting;
//        counting++;
//        
//        if (forPaging>100) {
//           // paging=1;
//            counting=2;
//            
//            [params setObject:[NSString stringWithFormat:@"%d", 100] forKey:@"count"];
//            [params setObject:[NSString stringWithFormat:@"%d", 1*counting] forKey:@"page"];
//            yomei=1;//1表示真
//        }
//        
//        [engine loadRequestWithMethodName:@"statuses/home_timeline.json"
//                               httpMethod:@"GET"
//                                   params:params
//                             postDataType:kWBRequestPostDataTypeNone
//                         httpHeaderFields:nil];   
//        [self engine:engine requestDidSucceedWithResult:self];
//        //[self.tableView reloadData];
//        [self.tableView reloadData];
//        self.view.userInteractionEnabled = YES;
//    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    
    
}

#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];
     */
}

-(void)dealloc
{
    [engine release];
    [timeLine release];
    [self.tableView release];
    //[flagShuaxin relea]
    [_downRefresh release];
    [_textText release];
    [_labelname release];
    [super dealloc];
}

@end

顺便这里做了个自制的版本跟新验证,接口是随便找了个公司的接口根据返回值判断的

当然必须先引入ASIHttpRequest(网上下载及解压的接口)中的文件

以下是执行方法

tempViewController.h

#import <UIKit/UIKit.h>
#import "ASINetworkQueue.h"
#import "ASIProgressDelegate.h"
@interface tempViewController : UIViewController<ASIHTTPRequestDelegate,ASIProgressDelegate,UIAlertViewDelegate>
{
    ASINetworkQueue *netWorkQueue;
    UIProgressView *zztjProView;
    UIButton        *OKButton;
    UIAlertView     *_alertView;//警告框1
    UIAlertView     *_alertView2;//警告框2
    UIAlertView     *_alertView3;
    NSThread                *_thread;
    UILabel         *_label;//显示多少M
    float           contentLength;
}
@property (nonatomic,assign)float contentLength;

-(void)VersionNumber;
@end


tempViewController.m

 

//
//  tempViewController.m
//  sinaWeiBo2
//
//  Created by Mac on 6/15/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "tempViewController.h"
#import "ASIHTTPRequest.h"
#import "ZipArchive.h"
#import "SZJsonParser.h"
#import "SZJsonParser.m"

@interface tempViewController ()

@end

@implementation tempViewController

@synthesize contentLength;

-(void)loadView
{
    [super loadView];
    
    [self VersionNumber];
}


-(void)VersionNumber
{
    _label=[[UILabel alloc]init];
    
   // zztjProView = [[UIProgressView alloc] initWithFrame:CGRectMake(75, 100, 150, 120)];
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSLog(@"Get document path:%@",[paths objectAtIndex:0]);
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"dataVersions"]==nil) {
        [[NSUserDefaults standardUserDefaults] setObject:@"1.0.0" forKey:@"dataVersions"];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:@"0.9.0" forKey:@"dataVersions"];
    
    NSLog(@"测试为%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"dataVersions"]);
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSString *myString=[NSString stringWithFormat:@"http://www.chibaofan.com/mapping/VerApi.php?ver=%@&showtype=json",[[NSUserDefaults standardUserDefaults] objectForKey:@"dataVersions"]];
    
    NSLog(@"网络地址为%@",myString);
    
    
    //解析json
    
    NSURL  *url = [NSURL URLWithString:myString];
    //定义一个url   
    //json get函数.
    NSMutableURLRequest* request = [NSMutableURLRequest new];  
    [request setURL:url];  
    [request setHTTPMethod:@"GET"];  
    NSURLResponse** response = NULL;  
    NSData* data = [NSURLConnection sendSynchronousRequest:request  
                                         returningResponse:response error:nil];
    NSString* strRet = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"version=%@",strRet);
    
    NSString *downing = [strRet jsonObject];
    
    // NSLog(@"解析出来为=%@",[strRet jsonObject]);
    
    
    NSLog(@"p爷版本号%@",downing);
    NSLog(@"当前版本号%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"dataVersions"]);
    
    
    
    if (downing==nil) {
        downing=[[NSUserDefaults standardUserDefaults] objectForKey:@"dataVersions"];
    }
    
    
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"dataVersions"]!=downing)
    {
        [self update];
        
        [[NSUserDefaults standardUserDefaults] setObject:downing forKey:@"dataVersions"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    zztjProView = [[UIProgressView alloc] init];
    
    
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    //报错机制
    _alertView3=[[UIAlertView alloc] initWithTitle:@"下载失败,请检查网络" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    _alertView3.delegate=self;
    _alertView3.tag=3;
    [_alertView2 dismissWithClickedButtonIndex:0 animated:YES];//警告框消失
    [_alertView3 show];
    
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders {
    //获取文件大小
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    
    float tempConLen=[[userDefaults objectForKey:[NSString stringWithFormat:@"loading"]] floatValue];
    if (tempConLen==0) {
        NSLog(@"蛋疼的进度条%@",request.contentLength);
        
       // request.contentLength=15.0*1024.0*1024.0;
        
        [userDefaults setObject:[NSNumber numberWithFloat:request.contentLength/1024.0/1024.0] forKey:[NSString stringWithFormat:@"loading"]];
        //[[NSUserDefaults standardUserDefaults] synchronize];
    }
}

-(void)setProgress:(float)newProgress
{
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    self.contentLength=[[userDefaults objectForKey:[NSString stringWithFormat:@"loading"]] floatValue];
    NSLog(@"newProgress is %@",newProgress);
    _label.text=[NSString stringWithFormat:@"%.2f/%.2fM",self.contentLength*newProgress,self.contentLength];
    zztjProView.progress=newProgress;
}

-(void)dealloc
{
    [netWorkQueue release];
    [super dealloc];
}

-(void)update
{
    _alertView=[[UIAlertView alloc] initWithTitle:@"软件有跟新" message:nil delegate:self cancelButtonTitle:@"稍后再说" otherButtonTitles:@"立即下载", nil];
    _alertView.delegate=self;
    _alertView.tag=1;
    [_alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1&&buttonIndex==1) {
        _alertView2=[[UIAlertView alloc] initWithTitle:@"下载中" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        _alertView2.delegate=self;
        zztjProView.frame=CGRectMake(_alertView2.frame.origin.x+50, _alertView2.frame.origin.y+50, 200, 20);
        _alertView2.tag=2;
        
        _label.frame=CGRectMake(_alertView2.frame.origin.x+100, _alertView2.frame.origin.y+70, 100, 20);
        //_label.backgroundColor=[UIColor redColor];
        _label.backgroundColor=[UIColor clearColor];
        
        
        [_alertView2 addSubview:_label];
        
        [_alertView2 addSubview:zztjProView];
        [_alertView2 show];
        
        netWorkQueue  = [[ASINetworkQueue alloc] init];
        [netWorkQueue reset];
        [netWorkQueue setShowAccurateProgress:YES];
        [netWorkQueue go];
        
        //初始化Documents路径
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        //初始化临时文件路径
        NSString *folderPath = [path stringByAppendingPathComponent:@"temp"];
        //创建文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //判断temp文件夹是否存在
        BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
        
        if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
            [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        //NSURL *downloadURL=[NSURL URLWithString:@"http://sinaweibosdkforoauth2.googlecode.com/files/SinaWeiBoSDK2.zip"];
        
        NSURL *downloadURL=[NSURL URLWithString:@"http://www.chibaofan.com/mapping/UpLoadFile/1339663807.zip"];
        
        ASIHTTPRequest *request=[[ASIHTTPRequest alloc] initWithURL:downloadURL];
        request.delegate=self;
        NSString *savePath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"huluwa1.zip"]];
        NSString *tempPath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"huluwa1.temp"]];
        [request setDownloadDestinationPath:savePath];
        [request setTemporaryFileDownloadPath:tempPath];
        //[request setDownloadProgressDelegate:self];
        [request setAllowResumeForFileDownloads:YES];
        [request setDownloadProgressDelegate:self];
        
        [netWorkQueue addOperation:request];
        [request release];
        
        NSString   *pathing=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString   *filePathing=[pathing stringByAppendingPathComponent:[NSString stringWithFormat:@"huluwa1.zip"]];
        NSString   *unZipPath=[pathing stringByAppendingPathComponent:[NSString stringWithFormat:@"huluwa1"]];
        
        ZipArchive *zip=[[ZipArchive alloc]init];
        
        [zip UnzipOpenFile:filePathing];
        
        [zip UnzipFileTo:unZipPath overWrite:YES];
        
        [zip UnzipCloseFile];
        
    }
    
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    _alertView3=[[UIAlertView alloc] initWithTitle:@"下载完成" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    _alertView3.tag=3;
    [_alertView3 show];
    [_alertView2 dismissWithClickedButtonIndex:0 animated:YES];//警告框消失
}

-(void)updateProgress:(NSNumber *)progress
{
    zztjProView.progress=[progress floatValue];
}
@end


posted on 2012-06-25 10:46  ownerblood  阅读(2874)  评论(0)    收藏  举报