会话维护在单触摸



我的应用基于银行域,需要会话处理。当应用程序空闲时(应用程序打开后没有任何触摸事件)必须在后台计算时间。

我在AppDelegate中处理应用程序进入前台和onResignInactive事件时的会话维护。

我需要实时处理应用程序。请帮我弄清楚这个特性

这里有obj-C的答案:iOS在不活动(没有用户交互)一段时间后执行操作

因此,在应用程序级别,您保留一个计时器,并在任何事件上重置它。然后,您可以在计时器的处理程序中执行您的业务(例如隐藏任何敏感信息)。

现在,进入代码。

首先,你必须创建UIApplication的子类,并确保你的UIApplication被实例化了:

//Main.cs
public class Application
{
    static void Main (string[] args)
    {
        //Here I specify the UIApplication name ("Application") in addition to the AppDelegate
        UIApplication.Main (args, "Application", "AppDelegate");
    }
}
//UIApplicationWithTimeout.cs
//The name should match with the one defined in Main.cs
[Register ("Application")]
public class UIApplicationWithTimeout : UIApplication
{
    const int TimeoutInSeconds = 60;
    NSTimer idleTimer;
    public override void SendEvent (UIEvent uievent)
    {
        base.SendEvent (uievent);
        if (idleTimer == null)
            ResetTimer ();
        var allTouches = uievent.AllTouches;
        if (allTouches != null && allTouches.Count > 0 && ((UITouch)allTouches.First ()).Phase == UITouchPhase.Began)
            ResetTimer ();
    }
    void ResetTimer ()
    {
        if (idleTimer != null)
            idleTimer.Invalidate ();
        idleTimer = NSTimer.CreateScheduledTimer (new TimeSpan (0, 0, TimeoutInSeconds), TimerExceeded);
    }
    void TimerExceeded ()
    {
        NSNotificationCenter.DefaultCenter.PostNotificationName ("timeoutNotification", null);
    }
}

这将确保你有一个计时器运行(注意:时间只从第一个事件开始),计时器将在任何触摸时重置自己,并且超时将发送通知(名为"timeoutNotification")。

你现在可以监听通知并对其进行操作(可能是推送一个cover ViewController)

//AppDelegate.cs
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
    UIWindow window;
    testViewController viewController;
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        window = new UIWindow (UIScreen.MainScreen.Bounds);
        viewController = new testViewController ();
        window.RootViewController = viewController;
        window.MakeKeyAndVisible ();
        //Listen to notifications !
        NSNotificationCenter.DefaultCenter.AddObserver ("timeoutNotification", ApplicationTimeout);
        return true;
    }
    void ApplicationTimeout (NSNotification notification)
    {
        Console.WriteLine ("Timeout !!!");
        //push any viewcontroller
    }
}

@Jason有一个很好的观点,你不应该依赖于客户端超时,你的会话管理,但你可能应该维护一个服务器状态和超时,以及

如果你把它写为一个web应用程序,你会把会话超时逻辑放在服务器上,而不是客户端。对于移动客户端,我也会采用相同的方法——让服务器管理会话和超时。

最新更新