4
-(void)loadRequest:(NSString *)jsonString{
receivedData = [[NSMutableData alloc]init];
urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:kURL]];
urlRequest=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   requestInformation =[[NSMutableURLRequest alloc]initWithURL:urlRequest cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[requestInformation setValue:khttpValue forHTTPHeaderField:kContentType];
[requestInformation setValue:@"value1" forHTTPHeaderField:@"key1"];

[requestInformation setHTTPMethod:kPost];
jsonData= [[NSString stringWithFormat:@"json=%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding];
[requestInformation setHTTPBody:jsonData];

connection = [[NSURLConnection alloc] initWithRequest:requestInformation delegate:self];
[connection start];
if(connection){
    NSLog(@"Connection succesfull");
}
else{
    NSLog(@"There is a error in connection");
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onFailedToUpload) userInfo:nil repeats:NO];

}
}

如何检查 else 部分是否被执行。我给出了不正确的 URL ,调用了 didfailwitherror 方法,但没有执行 else 部分。

4

1 回答 1

3

据我所知,connection对象总是被创建的。即使你的网址是错误的。任何错误都来自委托didFailWithError方法。您可能需要检查错误并正确进行。前任。如果超时,您可能希望在didFailWithError委托中重试。对于其他错误类型的处理方式不同。

如果您想在将其传递给之前处理损坏或错误的 url,NSURLConnection那么您需要自己做。

以下是使用时对您有用的代表NSURLConnection-

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response 
{
    NSLog("@Resp received");
    return;
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data 
{
    NSLog("@Data received");
    return
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error 
{
    NSLog("@ERROR: Achtung !: %@",[error localizedDescription]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH , 0),, ^{
        NSLog(@"FinishedLoading: In bg thread, do something with data here");

        dispatch_async( dispatch_get_main_queue(), ^{
            NSLog(@"FinishedLoading: In Main thread, access the UI here");
        });
    });
}
于 2012-09-10T06:49:26.423 回答