iPhone -trouble将来自webservice的加载数据加载到tableview中

时间:2011-11-14 21:48:45

标签: iphone web-services uitableview

我正在使用基于Window的应用程序,然后在appDelegate部分加载我的初始导航视图控制器 - 应用程序didFinishLaunchingwithOptions (更新)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

从web服务获取数据的方法通常是在[self getData]中以viewdidload ....的方法触发的。方法。

- (void)viewDidLoad
{
    [super viewDidLoad];


    if (_refreshHeaderView == nil) {

        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
            view.delegate = self;
        [self.tableView addSubview:view];
        _refreshHeaderView = view;
        [view release];

    }

    //  update the last update date
        [_refreshHeaderView refreshLastUpdatedDate];


        [self loadImages];


    HUDMB = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUDMB];

    HUDMB.dimBackground = YES;

        // Regiser for HUD callbacks so we can remove it from the window at the right time
    HUDMB.delegate = self;

    HUDMB.labelText = @"Loading..";

    [HUDMB show:TRUE];
    [self getData];
    [self.tableView reloadData];



}

在加载之前,如果用户未注册/没有凭据,则会将用户带到登录视图控制器。

- (void)loadView {
    [super loadView];

    if([Preferences isValid]?YES:NO)
    {

    }
    else
    {
        int r = arc4random() % 5;


        switch (r) {
            case 0:
            {
                loginViewController *sampleView = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil];
                [self.navigationController presentModalViewController:sampleView animated:YES];
                [sampleView release];
            }
                break;
            case 1:
            {
                loginViewController *sampleView = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil];                
                [sampleView setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
                [self.navigationController presentModalViewController:sampleView animated:YES];
                [sampleView release];
            }
                break;
            case 2:
            {
                loginViewController *sampleView = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil];
                [sampleView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
                [self.navigationController presentModalViewController:sampleView animated:YES];
                [sampleView release];
            }
                break;
            case 4:
            {
                loginViewController *sampleView = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil];
                [sampleView setModalTransitionStyle:UIModalTransitionStylePartialCurl];
                [self.navigationController presentModalViewController:sampleView animated:YES];
                [sampleView release];
            }
                break;
            case 3:
            {
                loginViewController *sampleView = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil];
                [sampleView setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
                [self.navigationController presentModalViewController:sampleView animated:YES];
                [sampleView release];
            }
                break;

            default:
                break;
        }  
    }


}

我认为getdata功能会带来很多麻烦。所以让我添加它以及我用于数据检索和序列化的相应函数。

-(void)getData{


    NSLog(@"loggin into call sheet page");

    [self getCallSheetData]; 

    NSLog(@"after call sheet");
}

- (void)getCallSheetData
{

    NSString *postCMD = @"Blah... Blah... Blah...";
    NSMutableData *postDataCMD = (NSMutableData *)[postCMD dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSURL *url = [NSURL URLWithString:[Preferences getURL]];
        //    NSLog(@"get call Sheet");
    NSString *postLengthCMD = [NSString stringWithFormat:@"%d", [postDataCMD length]+1];
        //    NSLog(@"The CS String: %@",[Preferences retriveSession]);
    requestCMD = [ASIHTTPRequest requestWithURL:url];
    [requestCMD setURL:url];
    [requestCMD addRequestHeader:@"Content-Length" value:postLengthCMD];
    [requestCMD addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded"];
    [requestCMD addRequestHeader:@"user-Agent" value:@"Mobile 1.4" ];
    [requestCMD addRequestHeader:@"Content-Language" value:@"en-US"];
    [requestCMD addRequestHeader:@"Accept-Encoding" value:@"gzip"];
    [requestCMD addRequestHeader:@"Cookie" value:[Preferences retriveSession]];


    [requestCMD setPostBody:postDataCMD]; 

    [requestCMD setDelegate:self];
    [requestCMD startAsynchronous];
}




- (void)requestFinished:(ASIHTTPRequest *)request
{

    NSMutableArray *CSArray = [[NSMutableArray alloc] init];
    if( [[request responseString] isEqualToString:@"OK"]){
        return;
    }

        // Use when fetching binary data
    NSData *responseData = [request responseData];
    NSDateFormatter *formatter1=[[NSDateFormatter alloc]init];
    [formatter1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [formatter1 setTimeZone:gmt];

    NSDateFormatter *formatterFinal=[[NSDateFormatter alloc]init];
    [formatterFinal setDateStyle:NSDateFormatterMediumStyle];
    [formatterFinal setTimeStyle: NSDateFormatterShortStyle];
    [formatterFinal setLocale:[NSLocale currentLocale]];

    JSONDecoder *jCSArray = [[JSONDecoder alloc]init];



    NSMutableArray *theObject = [jCSArray objectWithData:responseData];
        //        CallSheet= [NSMutableArray arrayWithCapacity:50];





    for(id key in theObject)
    {

        csr = [[CallSheetRecord alloc] init];

            //        cName,cCompany,cId,cMemberId,crcStatus,crcTarget,cImportance,cLastContact  
        csr.importance = @"1";
        csr.rcstatus = @"1";
        csr.rcTarget = @"1";
        csr.company = @"";
        csr.lastContact= @"";

        if([key valueForKey:@"firstName"]  != Nil) 
        {

            csr.name = [NSString stringWithFormat:@"%@",[key valueForKey:@"firstName"]] ;

            if ([key valueForKey:@"lastName"]  != Nil) {
                csr.name = [csr.name stringByAppendingString:@" "];
                csr.name = [csr.name stringByAppendingString:[NSString stringWithFormat:@"%@",[key valueForKey:@"lastName"]]];
            }

        }



        if([key valueForKey:@"company"] != Nil) 
        {

            csr.company = [NSString stringWithFormat:@"%@",[key valueForKey:@"company"]] ;


        }

        if([key valueForKey:@"memberId"]  != Nil) 
        {
            csr.memberId = [NSString stringWithFormat:@"%@",[key valueForKey:@"memberId"]] ;

        }

        if([key valueForKey:@"id"] != Nil) 
        {
            csr.id_ = [NSString stringWithFormat:@"%@",[key valueForKey:@"id"]] ;

        }

        if([key valueForKey:@"lastContact"]  != Nil) 
        {
            NSDate *finalDate =[formatter1 dateFromString:[NSString stringWithFormat:@"%@",[key valueForKey:@"lastContact"]]];


                //NSString *timeStamp = [formatter1 stringFromDate:[finalDate descriptionWithLocale:[NSLocale currentLocale]]];
                //NSLog(@"Time stamp : %@",[finalDate descriptionWithLocale:[NSLocale currentLocale]]);
                //NSLog(@"Time stamp : %@",timeStamp);
                //csr.lastContact = [key valueForKey:@"lastContact"];
            csr.lastContact = [formatterFinal stringFromDate:finalDate];


        }

        if([key valueForKey:@"importance"] != Nil) 
        {
            csr.importance = [NSString stringWithFormat:@"%@",[key valueForKey:@"importance"]];

        }

        if([key valueForKey:@"rcStatus"] != Nil) 
        {
            csr.rcstatus= [NSString stringWithFormat:@"%@",[key valueForKey:@"rcStatus"]] ;

        }

        if([key valueForKey:@"rcTarget"]  != Nil) 
        {
            csr.rcTarget = [NSString stringWithFormat:@"%@",[key valueForKey:@"rcTarget"]] ;

        }


        [CSArray addObject:csr]; 



    }
    CSD = [CSArray mutableCopy];

    [CSArray release];
    [formatter1 release];
    [formatterFinal release];

        //CallSheetArray = [CSArray mutableCopy];
        //[csr release];
    [jCSArray release];

    [HUDMB hide:TRUE];
    [self.tableView reloadData];







}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    UIAlertView *message = [[[UIAlertView alloc] initWithTitle:@"Hello World!"
                                                      message:[NSString stringWithFormat:@"%@",error]
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil]autorelease];

    [message show];


}

然后我尝试用 [self getData]; 加载表格,我使用asiHTTP使用webservice调用make ..对于这个问题,我们可以说需要3秒的时间来获取数据,然后反序列化。现在......我的问题是它在以后的运行中运行,因为我将用户名和密码存储在一个安全的位置......但在第一个实例....我无法获得数据tableview ...我尝试了很多东西......

1。最初数据获取方法是在一个不同的方法..所以我认为这可能是问题,因为然后移动它与tbleviewController(navigationController)相同的地方

2。我事件在数据解析和反序列化功能结束时放入了Reload数据......没有任何反应。

第3。屏幕是黑屏,在应用程序的连续启动中没有显示任何内容5秒钟。所以我们可以为此实现类似的MBPorgressHUD。

任何人都可以帮助这些方案和指导,从这里采取什么样的路径。 ......

更新: 赏金只需回答2个问题,你可以做到最好...属性是我试过的东西,但它不起作用......但我的问题不是那个...我的问题是我的屏幕无法加载数据登录后直到我执行“拉动刷新”的web服务。下一次最终启动我的应用程序需要大约5秒钟来显示屏幕(直到它显示黑屏)...什么是向最终用户显示应用程序的最佳方式当他们进入应用程序时。我不希望用户认为该应用程序无法正常工作或对他们的手机造成了不良影响。

2 个答案:

答案 0 :(得分:0)

这里有许多潜在的问题。第一个与[self getData]相关 - 是否阻止?

<强> 1。 getData阻塞(同步)

如果此方法阻止(即不立即返回),那么这将解释为什么您在屏幕上看不到任何内容几秒钟。您当前正在主线程中调用此方法,因此它将阻止UI更新,直到完成。

你可以通过这样做让它在后台运行:

- (void) getDataInBackgroundThread
{
   NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];

   [self getData];

   // force the table to redraw - UI operations must be on the main thread
   [tableView performSelectorOnMainThread:@selector( reloadData )];

   [pool drain];
}

在你的主代码中,现在不是调用[self getData]调用[self getDataInBackgroundThread];

<强> 2。 getData没有阻塞(异步)

即使getData被阻止,如果它在主线程中运行,它仍然会导致UI挂起。此外,如果它使用大量处理器时间,它将减慢UI并使外观不在后台运行。

要解决这个问题,你需要确保getData的冗长操作确实没有在主线程中运行,并且经常进入sleep()调用以给UI一些时间来更新。

答案 1 :(得分:0)

你还没有提供足够的信息让人们真正提供帮助,我们只是在猜测。

  1. 延迟很可能是由getData引起的。尝试对其进行评论或将其括在NSLog语句中进行验证。

  2. 您应该向我们展示更多代码,特别是getData中发生的事情以及与加载数据相关的任何委托或通知处理实现。

  3. 您无需在[tableView reloadData]中明确呼叫viewDidLoadtableView会在第一次显示时自动加载数据。

  4. 正如@dmatt所说,如果你是异步加载数据,那么getData会立即返回而没有延迟。在数据加载和序列化完成后,您通常会响应委托消息或通知(取决于您如何加载数据)来重新加载表。

    如果有足够的信息,很多人都很乐意尝试帮助你。特别是当你提供赏金时。