如果webview中没有互联网连接,iOS会显示警报

时间:2014-06-15 18:32:03

标签: ios webview

我正在使用xCode中的简单webview制作应用程序。如果没有可用的互联网连接,我希望通知用户。当没有互联网连接时,会弹出一个告诉你“没有可用的互联网连接”和两个选项 - 再试一次,然后取消。我该怎么做呢?我是初学者所以请解释一下。

ViewController.m

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@end

@implementation ViewController

@synthesize webView;

- (void)viewDidLoad
{

NSURL *url = [NSURL URLWithString:@"http://MyWebPage.com"];
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
webView.delegate = self;
[webView loadRequest:requestURL];

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

1 个答案:

答案 0 :(得分:1)

我同意Leo,但我会做一个简短的尝试来解释它:

  1. 从apple或github获取类Reachability:
    - 这是一个允许您检查互联网的课程/看看是否可以到达特定主机/ ....

  2. 在您的viewController中
  3. 在加载网站之前检查可达性。 - 也许在viewWillAppear

    - (void)viewWillAppear:(BOOL)animated {
            [super viewWillAppear:animated];        
            _reachability = [Reachability reachabilityForInternetConnection];
            [self handleReachability];
    
            //optional monitor
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(handleReachability: )
                                                         name:@"kReachabilityChangedNotification" object:nil];
    
            [_reachability startNotifier]; //! don't forget to remove the notification in viewWillDisappear  
    
        }
    
  4. 实现句柄方法,例如显示一个简单的UIAlertView:

    -(void)handleReachability:(NSNotificationCenter*)notification{
        NetworkStatus netStatus = [reach currentReachabilityStatus];
    
        if(netStatus == NotReachable) {
            [self setNoInternet:YES];
            // what happens when network/server down: 
            if([webView isLoading]) {
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                [webView stopLoading];
                hasLoaded = NO;
            }
    
        }else {
            [self setNoInternet:NO];
            if(![webView isLoading] && !hasLoaded) {
                hasLoaded = NO;
                [self load];
            }
        }
    }