Skip to content

Instantly share code, notes, and snippets.

@zhaozzq
Last active June 7, 2020 06:38
Show Gist options
  • Save zhaozzq/0a883880d2a88de1a59165e12341c609 to your computer and use it in GitHub Desktop.
Save zhaozzq/0a883880d2a88de1a59165e12341c609 to your computer and use it in GitHub Desktop.
// 进入后台
UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
// 结束应用
DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
  UIApplication.shared.perform(Selector(("terminateWithSuccess")))
}
//Objective-C
[[UIControl new] sendAction:@selector(suspend) to:[UIApplication sharedApplication] forEvent:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wundeclared-selector"
    [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
    #pragma clang diagnostic pop
});

需要注意的是,单独第一行就可以达到 有动画回到桌面程序进入后台的目的,单独第二行 没有动画回到桌面并终止应用,两行同时使用可以 动画回到桌面并终止应用。 根据需要选择其中一个或两个一起使用。

在 iOS 12 下,延迟 1.25 秒结束应用不会出问题。

原文 iOS程序内通过代码回到桌面

        DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: DispatchTime.now() + 2) {
            let url = URL(string: "https://raw.githubusercontent.com/zhaozzq/apps/master/setup.json")!
            let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
                guard let data = data else { return }
                //print(String(data: data, encoding: .utf8)!)
                if let json = try? JSONSerialization.jsonObject(with: data), let info = json as? [String: Any], let toggle = info["toggle"] as? Bool, !toggle  {
                    DispatchQueue.main.async {
                        // 进入后台
                        UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
                        // 结束应用
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
                            UIApplication.shared.perform(Selector(("terminateWithSuccess")))
                        }
                    }
                }
            }
            task.resume()
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment