我正在开发通用应用程序。那时我的应用程序是打开的,我正在检查是否存在互联网连接。目的是我添加AFNETWORKING框架。问题是我正在调试我的代码{{1这个函数没有执行控件去外面。这是我的要求是互联网连接不可用意味着它显示弹出“请连接互联网”就像互联网连接意味着它正常打开。我发布我的代码库
[manager GET:APIscript parameters:nil success:^(NSURLSessionDataTask *task, id responseObject)
这里这一行(NSURL *baseURL = [NSURL URLWithString:@"https://www.google.co.in"];
NSString *APIscript=@"/webhp";
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setTimeoutInterval:20.0];
[manager GET:APIscript parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
if ([r statusCode] == 200) {
//Do success stuff
}
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alertView show];
//do failure stuff
}];
)只是没有执行。请指导我解决这个问题。谢谢。
答案 0 :(得分:1)
从Github下载rateability lib并编写此代码......
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setUpRechability];
}
在appdelegate中的didFinishLaunchingWithOptions中调用此方法
-(void)setUpRechability
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNetworkChange:)
name:kReachabilityChangedNotification
object:nil];
netReachability = [Reachability reachabilityForInternetConnection];
[netReachability startNotifier];
[self handleNetworkChange:nil];
}
此方法将在互联网状态发生变化时调用..
- (void) handleNetworkChange:(NSNotification *)notice
{
NetworkStatus remoteHostStatus = [netReachability currentReachabilityStatus];
if (remoteHostStatus == NotReachable) {NSLog(@"no"); hasInet=NO; }
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); hasInet=YES; }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); hasInet=YES; }
if (!hasInet)
{
[HUD hide:YES];
HUD=nil;
}
}
答案 1 :(得分:0)
您可以尝试使用Apple Reachability Sample或者您可以使用AFHTTPRequestOperationManager,这样更简单,更容易。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];