我正在用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
最佳答案
我同意狮子座,但我会尽力解释一下:
从苹果或github获取类可达性:
-这是一类,可让您检查互联网/查看是否可以访问特定主机/...。
在您的viewController中,在加载网站之前检查是否可访问。
-也许在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
}
实施句柄方法显示一个简单的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];
}
}
}
关于ios - 如果Webview中没有互联网连接,iOS会显示警报,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24232787/