检查 iPhone 中的 NSURLConnection 是否未成功?

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部分没有被执行。


1
如果您想处理错误的URL,则应在URL上进行检查,而不是连接。请参见:https://dev59.com/_XM_5IYBdhLWcg3wPAVF ... https://dev59.com/x0XRa4cB1Zd3GeqPsHk2 - Mazyod
1个回答

3
据我所知,connection对象总是会被创建,即使您的url是错误的。任何错误都将传递到代理方法didFailWithError中。您可能需要检查错误并采取适当的措施。例如,如果是超时,您可能希望在didFailWithError代理中重试。对于其他类型的错误,需要进行不同的处理。
如果您想在将其传递给NSURLConnection之前处理坏的或错误的url,则需要自己进行处理。
以下是在使用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");
        });
    });
}

感谢您宝贵的回复。 - Ben10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接