0

我正在尝试从我的服务器获取更新。我希望它拥有最新信息,所以我正在运行一个页面,如果响应是"Complete"而不是响应,"Error"那么我将继续使用 Update 方法从xml文件中获取最新信息。我的问题是在我的“主要”函数中的所有代码完成之前,不会调用委托方法。到那时,代码已经通过我的 if 语句检查responseSuccessisTRUEFALSE. 我认为这是因为 NSURLConnection 是异步的……但我不确定如何修复它。如果我需要提供更多代码/信息,请告诉我。谢谢!

主要的

    if (UpdatingFlag)
    {
        NSLog(@"Cannot update while updating is in process...");
    } else {
        // run updates before getting information
        [self getResponse:@"http://url/path/to/file?function=myvalue"];

        [self setBottomBarToUpdating:@"Processing Please Wait..."];

        dispatch_queue_t queue = dispatch_queue_create("updateQueue", DISPATCH_QUEUE_CONCURRENT);

        UpdatingFlag = TRUE;

        if(responseSuccess)
        {
           dispatch_async(dispatch_get_main_queue(),^ {
              [self setBottomBarToUpdating:@"Updating..."];
              [self updateFromXMLFile:@"https://url/path/to/file.xml"];
           });
        }

        UpdatingFlag = FALSE;

        dispatch_barrier_async(queue,^ {
            dispatch_async(dispatch_get_main_queue(), ^{
                 [self setBottomBarToUpdated];
            });
        });

}

获取响应方法

- (void) getResponse:(NSString *)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:45.0];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];

    if (connection) {NSLog(@"Connecting...");
    } else {NSLog(@"Didn't Connect Error...");}
}

委托方法

#pragma mark NSURLConnection methods

- (void)connection:(NSURLConnection *)conn didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSLog(@"Did Receive Challenge");

    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential = [NSURLCredential credentialWithUser:@"user" password:@"pass" persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];

        NSLog(@"Invalid Username and Password");

        UIAlertView * userNameAlert = [[UIAlertView alloc]initWithTitle:@"Error"
                                                                message:@"ErrorMsg"
                                                               delegate:self
                                                      cancelButtonTitle:nil
                                                      otherButtonTitles:@"OK", nil];
        [userNameAlert show];

    }

}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    NSLog(@"Received Data Packet...");
    response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error, %@", error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    NSLog(@"Finished Loading");
    if([response rangeOfString:@"Complete"].location == NSNotFound) {
        // success
        responseSuccess = FALSE;
    } else {
        // failed
        responseSuccess = TRUE;
    }
}

- (BOOL)connection:(NSURLConnection *)conn canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return YES;
}
4

1 回答 1

0

从服务器获取更新后要运行的任何代码都需要移动到(或从中调用)connectionDidFinishLoading: 方法。因此,您可以摆脱这些标志,而只在主代码中调用 getResponse。

于 2012-11-02T15:53:07.127 回答