2

我编写了一个将网站数据解析为表格视图的应用程序。

我还使用 MBProgressHUD 在解析发生时向用户显示反馈。

我从 viewDidLoad 调用加载方法:

- (void)viewDidLoad {
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    noConnectionAlert = [[UIAlertView alloc] initWithTitle:@"אין מידע להצגה"
                                               message:@"אין אפשרות להתחבר לאינטרנט."
                                              delegate:self cancelButtonTitle:@"אישור"
                                     otherButtonTitles: nil];

    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"טוען...";

    [self.view addSubview:HUD];
    [HUD showWhileExecuting:@selector(loadReports) 
                  onTarget:self withObject:nil animated:YES];

    BOOL hasConnection = [self hasInternetConnection];

    if (!hasConnection) {
       [noConnectionAlert show];
    } else {
       [self loadReports];
    }

}

我有一个 TabBar,所以这个加载发生在第一个和第二个视图中。问题是当应用程序正在运行时以及当我点击 TabBar 中的第二个选项卡时,我注意到延迟(当互联网连接速度很慢时)。

是否有另一种方法可以使应用程序尽可能快地启动(或在点击时移至下一个选项卡)(并在加载数据时显示 HUD)?

编辑:

这是负载报告:

- (void)loadReports {
NSURL *reportsUrl = [NSURL URLWithString:@"http://www.iba.org.il/moked/index.aspx?   classto=mokedTraffic"];
NSData *reportsHtmlData = [NSData dataWithContentsOfURL:reportsUrl];


NSString *encodedStringData = [[NSString alloc] initWithData:reportsHtmlData    encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsHebrew)];
NSLog(@"%@", encodedStringData);
NSData *reportsHtmlDataEncoded = [encodedStringData dataUsingEncoding:NSUTF16StringEncoding];

TFHpple *reportsParser = [TFHpple hppleWithHTMLData:reportsHtmlDataEncoded];
NSString *reportsXpathQueryString = @"//table//tr//td";
NSArray *reportsNodes = [reportsParser searchWithXPathQuery:reportsXpathQueryString];

for (int i = 0; i < reportsNodes.count - 1; i++) {
    TFHppleElement *nodeFirstChild = [(TFHppleElement *)reportsNodes[i] firstChild];
    if ([[nodeFirstChild tagName] isEqualToString:@"text"]) {
        NSLog(@"%@", reportsNodes[i]);
        NSLog(@"%@", nodeFirstChild);
    }
}
NSMutableArray *newReports = [[NSMutableArray alloc] initWithCapacity:0];

NSString *thisAttribute = [[NSString alloc] init];
NSDictionary *thisNode = [[NSDictionary alloc] init];
for (TFHppleElement *element in reportsNodes){
    NSString *str = [[element firstChild] content];
    if (str != NULL) {
        TFHppleElement *firstChild = [element firstChild];
        NSArray *childStrong = [element childrenWithTagName:@"strong"];
        NSLog(@"%@", childStrong);
        NSString *mokedContent;
        for (TFHppleElement *strongElement in childStrong){
            NSLog(@"%@", [[[strongElement firstChild] firstChild] content]);
            mokedContent = [[[strongElement firstChild] firstChild] content];
        }

        thisNode = [element attributes];
        thisAttribute = (NSString *)[thisNode objectForKey:@"width"];
        if (thisAttribute == NULL) {
            NSArray *spanChildren = [element childrenWithTagName:@"span"];
            if (spanChildren.count > 0) {
                TFHppleElement *spanChild = [spanChildren objectAtIndex:0];
                NSString *spanContent = [[spanChild firstChild] content];
                NSRange firstRange = [spanContent rangeOfString:@"\u00a0("];
                BOOL isFound = NO;
                if (firstRange.length > 0){
                    isFound = YES;
                    NSLog(@"String contains");
                }
                else {
                    NSLog(@"No found in string");
                }
                NSString *result = [spanContent stringByReplacingCharactersInRange:firstRange    withString:@""];
                NSRange secondRange = [result rangeOfString:@")\u00a0"];
                NSString *time = [result stringByReplacingCharactersInRange:secondRange withString:@""];
                NSLog(@"%@", time);

                ORDKolIsrael *kolIsraelTraffic = [[ORDKolIsrael alloc] init];
                [newReports addObject:kolIsraelTraffic];

                NSString *reportFinal = [firstChild content];
                kolIsraelTraffic.kolIsraelReport = reportFinal;

                kolIsraelTraffic.kolIsraelTime = time;
                NSLog(@"%@", kolIsraelTraffic.kolIsraelReport);
            }

        }
    }
}
_reports = newReports;
[self.tableView reloadData];
}

编辑(2):

我添加了一个异步获取数据的方法:

    - (void)getDataFromUrlString:(NSString *)string
    {
       //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:string];

    //prepare NSURL with newly created string
    NSURL *url = [NSURL URLWithString:databaseURL];

    //AsynchronousRequest to grab the data
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if ([data length] > 0 && error == nil){
             [self loadReports:data];
         }else if ([data length] == 0 && error == nil){

         }else if (error != nil && error.code == NSURLErrorTimedOut){ //used this NSURLErrorTimedOut from foundation error responses

         }else if (error != nil){

         }
     }];
   }

我从 viewDidLoad 调用此方法,但 tableview 没有获取数据(空表),尽管当我调试代码时,我可以在 CellForRowAtIndexPath 中看到所需的数据。知道为什么吗?

4

1 回答 1

1
NSData *reportsHtmlData = [NSData dataWithContentsOfURL:reportsUrl];

此行将暂停您的程序,直到请求返回。如果您不希望用户与视图交互,则设置异步请求并显示在请求完成之前他们无法交互的视图。

所以,你想要一个异步连接。阅读NSURLConnection上的文档。

简而言之,您将要创建一个连接对象:

NSURLConnection *connection = [NSURLConnection initWithRequest:request
                                                      delegate:self];

然后响应一些委托方法,例如:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

最后,启动它:

[connection start];

或者你可以使用像AFNetworking这样的库来简化所有这些设置。

于 2013-01-30T18:26:36.887 回答