Интеграция MBProgressHUD с двумя классами - PullRequest
0 голосов
/ 13 октября 2011

Я пытаюсь правильно интегрировать MBProgressHUD в проект, пока я загружаю и обрабатываю некоторые данные.Прости меня за мое невежество, если я спрашиваю глупости, но я полный нуб ...

У меня есть класс "Data", который обрабатывает мои HTTPRequest, поэтому я считаю, что это подходящее место для размещениянекоторые вещи в:

-(void)resolve
{
    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[[NSURL alloc] initWithString:[self url]]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    NSLog(@"Resolving content from: %@",[self url]);
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [[NSMutableData data] retain];
    } else {
        NSLog(@"Content - resolve: connection failed");
    }

    // Here is the part that it makes me crazy...

    HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];

    return;

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    expectedLength = [response expectedContentLength];
    currentLength = 0;
    HUD.mode = MBProgressHUDModeDeterminate;
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    currentLength += [data length];
    HUD.progress = currentLength / (float)expectedLength;

    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.

    [receivedData appendData:data];
    return;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [HUD hide:YES];
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];

    // inform the user
    NSLog(@"Content - Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    return;
}

Теперь я знаю, что помещать «showHUDaddedTo» в - - (void) - неправильный путь ...

Я вызываю эту функцию данных изконтроллер представления с IBaction как это:

-(IBAction) btnClicked:(id) sender {
    if ([[issue status] intValue] == 1 ) // issue is not downloaded
    {

        [(Content *)[issue content] resolve];
        //HUD = [[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES] retain];




    }
    else // issue is downloaded - needs to be archived
    {
        NSError * error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:[(Content *)[issue content] path]  error:&error];
        if (error) {
            // implement error handling

        }
        else {
            Content * c = (Content *)[issue content];
            [c setPath:@""];
            [issue setStatus:[NSNumber numberWithInt:1]];
            [buttonView setTitle:@"Download" forState:UIControlStateNormal];
            [gotoIssue setTitle:@"..." forState:UIControlStateNormal];


            // notify all interested parties of the archived content
            [[NSNotificationCenter defaultCenter] postNotificationName:@"contentArchived" object:self]; // make sure its persisted!

        }



    }
}

Проще говоря: я хотел бы вызвать все вещи MBProgressHUD из моего файла Conten.m в тот момент, когда я нажимаю кнопку загрузки в моем файле IssueController.m,Я думаю, теперь вы видите, где моя проблема: я не кодер ;-) Любая помощь приветствуется.

Приветствия,

sandor

1 Ответ

0 голосов
/ 30 января 2012

Я бы попытался использовать метод HUD showWhileExecuting. Оберните ваши звонки новым методом и вызовите его, чтобы загрузить вашу информацию. Когда ваш метод завершится, так же как и ваш HUD.

Кроме того, есть ли причина, почему вы сохраняете свои звонки для HUD? Я не видел этого раньше, и я не уверен, нужно ли вам сохранять их, поскольку они автоматически выпускаются.

...