我想从我的MainViewController.m
中调用一个webService,它位于我的DataManagement.m
类中。我所做的是创建一个单例并使用以下行启动它:
[[DataManagement sharedManager] callWebService:url withBytes:bytes];
它工作正常。在这种情况下调用connectionDidFinishLoading
。
但是,如果我想用另一个Reachability.m
类检查Internet(回调块将错误返回为nil。所以这意味着存在Internet连接)。当我然后启动相同的代码时,从不调用connectionDidFinishLoading
方法。我是否必须使用代理人或其他人?
DataManagement.m
+ (instancetype) sharedManager
{
static DataManagement *sharedManager = nil;
if (sharedManager == nil)
{
sharedManager = [[self alloc] init];
}
return sharedManager;
}
- (void)callWebService:(NSString *)url withBytes:(NSString *) bytes
{
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSString *url_string = [bytes stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[request setURL:[NSURL URLWithString:[url stringByAppendingString: url_string]]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:timeOut];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
...
}
MainViewController.m
不起作用:
-(void)viewDidLoad
{
...
[Reachability checkInternetConnectivityWithUrl: url_server WithSuccessCompletion:^(NSError *error) {
if (error == nil)
{
[[DataManagement sharedManager] callWebService:url withBytes:bytes];
}
else
{
NSLog(@"No internet connection");
}
}];
...
}
作品:
-(void)viewDidLoad
{
...
[[DataManagement sharedManager] callWebService:url withBytes:bytes];
...
}
您的使用仅用于检查互联网连接,但使用此功能进行连接或未检查。它会工作正常。
- (BOOL)connected
{
Reachability *reachability = [Reachability
reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability
currentReachabilityStatus];
return networkStatus != NotReachable;
}
-(void)viewDidLoad
{
...
if ([self connected])
{
[[DataManagement sharedManager] callWebService:url
withBytes:bytes];
}
else
{
NSLog(@"No internet connection");
}
}
}