我正在使用以下代码检查服务器连接,但是“连接”始终为TRUE。
我知道不建议使用'initWithRequest:delegate:':建议改用NSURLSession,但是为了简化起见,我宁愿继续使用它,因为实现起来NSURLSession似乎要复杂得多。
有什么建议可以使其正常工作吗?
NSURL *url = nil;
NSMutableURLRequest *request = nil;
NSString *getURL = [NSString stringWithFormat:@"%@?TEST=%@",URL, str];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection) //Always true!!!
{
mutableData = [NSMutableData new];
NSLog(@"SERVER CONNECTION OK");
}
else
{
NSLog(@"NO SERVER CONNECTION");
}
答案 0 :(得分:0)
connection是您创建的NSURLConnection对象。如果创建,它将返回true。
问题是您没有处理可通过以下委托函数使用的响应数据:
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
您应该在didFailWithError中放置一个日志,以检查您的连接是否成功。
我非常确定您没有尝试过NSURLSession,但是您应该这样做,因为NSURLSession可以作为块编写,这使得编写代码(没有委托)更加容易。 实际上,NSURLSession比NSURLConnection更容易实现。