应用程序进入前台时如何刷新UIWebView? [英] How to refresh UIWebView when app comes to foreground?

查看:47
本文介绍了应用程序进入前台时如何刷新UIWebView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我的应用程序出现在前台时,我都希望刷新UIWebView.我在ViewController.m中真正拥有的只是一种检查Internet访问(hasInternet)和viewDidLoad的方法.

I would like to refresh a UIWebView whenever my app comes to the foreground. All I really have in my ViewController.m is a method that checks for internet access (hasInternet) and viewDidLoad.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize webview;

-(BOOL)hasInternet{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStats = [reach currentReachabilityStatus];

    if (internetStats == NotReachable) {
        UIAlertView *alertOne = [[UIAlertView alloc] initWithTitle:@"You're not connected to the internet." message:@"Please connect to the internet and restart the app." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertOne show];
    }

    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self hasInternet];
    [webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://warm-chamber-7399.herokuapp.com/"]] ];
}

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

@end

有关如何启用此功能的任何建议?它会放在AppDelegate中还是在ViewController.m中创建另一个方法?

Any advice on how to enable this functionality? Does it go in AppDelegate or do I create another method within ViewController.m?

推荐答案

您应该在 ViewController viewDidLoad 方法中注册 UIApplicationWillEnterForegroundNotification 而且只要应用程序从后台返回,您都可以使用注册通知的方法来做您想做的任何事情.当应用程序从后台返回到前景时,不会调用 ViewController viewWillAppear viewDidAppear .

You should register a UIApplicationWillEnterForegroundNotification in your ViewController's viewDidLoad method and whenever app comes back from background you can do whatever you want to do in the method registered for notification. ViewController's viewWillAppear or viewDidAppear won't be called when app comes back from background to foreground.

-(void)viewDidLoad{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff)

    name:UIApplicationWillEnterForegroundNotification object:nil];
}

-(void)doYourStuff{

  [webview reload];
}

别忘了取消注册您所注册的通知.

Don't forget to unregister the notification you are registered for.

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

注意,如果您为 UIApplicationDidBecomeActiveNotification 注册了 viewController ,则每次您的应用激活时都会调用您的方法,注册此通知.

Note if you register your viewController for UIApplicationDidBecomeActiveNotification then your method would be called everytime your app becomes active, It would not be appropriate to register for this notification.

这篇关于应用程序进入前台时如何刷新UIWebView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆