我通过POST HTTP方法调用URL。当我没有连接到3G或WiFi时,它将永远不会正确获取URL,并且永远不会正确地从URL获得响应。 通过邮件连接:
NSString *URL = [NSString stringWithFormat:@"http://www.abc.com/webservices/client_server.cfc];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSString *time_stamp =[NSString stringWithFormat:@"time_stamp=%@", self.today];
NSData *postData = [time_stamp dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *URLRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[URLRequest setURL:[NSURL URLWithString:URL]];
[exhURLRequest setHTTPMethod:@"POST"];
[URLRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[URLRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[URLRequest setHTTPBody:postData];
self.connection =[[[NSURLConnection alloc] initWithRequest:URLRequest delegate:self] autorelease];
NSAssert(self.connection != nil, @"Failure to create URL connection.");
我正在检查是否通过以下方式得到答复:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// check for HTTP status code for proxy authentication failures
// anything in the 200 to 299 range is considered successful
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (([httpResponse statusCode]/100) == 2) {
self.data = [NSMutableData data];
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(@"HTTP Error",
@"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
[self handleError:error];
}
}
但是有些如何在没有连接URL的情况下让我说当我在地铁或其他东西时,我无法连接到URL并且它会抛出“URL NOT SUPPORTED”。如何避免这种情况并允许应用程序向前推进而不会抛出这样的错误?如果有人使用离线重定向到应用程序而不继续在前面屏幕上等待用户。
答案 0 :(得分:3)
下载apple的Reachability示例代码。将Reachability.h + .m添加到您的项目中。链接SystemConfiguration框架。然后像这样使用他们的Reachability类。
#import "Reachability.h"
用于WiFi:
-(void)doStuff{
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
if (wifi.currentReachabilityStatus == ReachableViaWiFi){
// do connected stuff
}
else {
// do offline stuff
}
}
对于Wifi或3G:
-(void)doStuff{
NetworkStatus connectivity = [Reachability reachabilityForInternetConnection].currentReachabilityStatus;
if (connectivity == ReachableViaWiFi || connectivity == ReachableViaWWAN){
// do connected stuff
}
else {
// do offline stuff
}
}
如果您将继续执行网络任务,请将可访问性对象添加到您的班级。这将提高性能并允许您使用它的通知程序。
答案 1 :(得分:1)
有些时候这个“URL NOT SUPPORTED错误”是由于url没有编码。
这个编码网址使用this.or有很多方法在互联网上。 不要编码整个网址或基本网址(因为它将编码“:”和“/”也可能导致错误) 只有特殊字符需要编码,如&,@ etc。
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)pathRequest,
NULL,
(CFStringRef)@"!*'();:@&=+$,%#[]",
kCFStringEncodingUTF8 ));
答案 2 :(得分:0)
How to check for an active Internet connection on iOS or OSX?
使用此处提出的解决方案避免在没有有效的互联网连接时发送请求。简单。