CFNetwork错误:由于URL格式错误,连接失败

时间:2012-09-12 07:57:59

标签: iphone ios debugging cfnetwork

在运行iphone app时,我多次遇到以下错误

The connection failed due to a malformed URL

CFNetwork Error Codes Reference,我收到了CFNetwork触发此错误的信息

  • 何时以及为何触发此错误?
  • 如何摆脱这个错误?

1 个答案:

答案 0 :(得分:2)

NSURLConnection有一个方法canHandleRequest,它会返回一个布尔值,无论url是否有效,例如

NSString *strUrl = [NSString stringWithFormat:@"http://test.com/stopBoard/%i",busStopCode];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url 
                                              cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
                                          timeoutInterval:20.0];
// a cache policy of NO must be used otherwise the previous query is used if the phone is not online

BOOL canGo = [NSURLConnection canHandleRequest:request];
if(canGo){
    connection = [[NSURLConnection alloc] initWithRequest:request 
                                                 delegate:self 
                                         startImmediately:YES];


} else {
    self.errorMessage = @"\n\nurl check failed\n\n";
    return NO;
}