美文网首页
iOS 应用进入后台继续接收消息

iOS 应用进入后台继续接收消息

作者: 达若漠沙 | 来源:发表于2018-08-09 19:56 被阅读301次

    应用开发中,常常有这样的场景,app进入后台后,比如手机息屏后,系统默认会断开此应用的网络连接,消息无法送达。当然这里我们不讨论推送这种方式,而是让程序在后台依然运行,能够保持网络通畅,收到服务器的消息。
    很简单,在 applicationDidEnterBackground 生命周期方法里添加以下代码:

    - (void)applicationDidEnterBackground:(UIApplication *)application {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        UIApplication*   app = [UIApplication sharedApplication];
        __block    UIBackgroundTaskIdentifier bgTask;
        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (bgTask != UIBackgroundTaskInvalid)
                {
                    bgTask = UIBackgroundTaskInvalid;
                }
            });
        }];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (bgTask != UIBackgroundTaskInvalid)
                {
                    bgTask = UIBackgroundTaskInvalid;
                }
            });
        });
    }
    

    于是,在很长一段时间内,app依然可以收到消息,且静默执行逻辑,不过这个时间也是有限制的,最长不会超过10min.

    相关文章

      网友评论

          本文标题:iOS 应用进入后台继续接收消息

          本文链接:https://www.haomeiwen.com/subject/njncbftx.html