2012-09-12 55 views
1

在运行iPhone应用程序,有好几次我得到了以下错误CFNetwork的错误:连接失败,因为一个错误的URL

The connection failed due to a malformed URL 

CFNetwork Error Codes Reference,我得到的信息,这个错误被CFNetwork的

    触发
  • 何时以及为什么会触发此错误?
  • 如何摆脱这个错误?
+0

http://stackoverflow.com/questions/5370009/iphone-sdk-check-validity-of-urls-with-nsurl-not-working – janusbalatbat

回答

2

NSURLConnection有一个canHandleRequest方法,无论url是否有效,它都会返回一个boolean值。

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; 
} 
相关问题