首页 > 解决方案 > 在 Swift 上以编程方式将应用程序置于前台

问题描述

我测试过:

UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)

这是为了将应用程序放在后台并且它可以工作。

如何将应用程序放回前台?

我试过了:

UIControl().sendAction(#selector(URLSessionTask.resume), to: UIApplication.shared, for: nil)

但最终它崩溃了......

谢谢

标签: iosswiftforeground

解决方案


更新:

由于您表示您正在寻找任何技术解决方案,即使是那些与 App Store 或 Apple 条款不兼容的解决方案,这应该可以使用 Private API 来实现LSApplicationWorkspace: openApplicationWithBundleID。尝试这样的事情:

创建一个 .h 文件并设置LSApplicationWorkspace类的接口并列出所需的方法。您将需要#import "PrivateHeaders.h"在您的桥接头中。

//
// PrivateHeaders.h
//

#ifndef PrivateHeaders_h
#define PrivateHeaders_h

@interface LSApplicationWorkspace : NSObject

- (bool)openApplicationWithBundleID:(id)arg1;

@end

#endif /* PrivateHeaders_h */

然后,您应该能够调用此函数并将应用程序的捆绑标识符作为字符串传递。

//
// SomeClass.swift
//

import MobileCoreServices

let workspace = LSApplicationWorkspace()

/**
 Launch an App given its bundle identifier
 - parameter bundleIdentifier: The bundle identifier of the app to launch
 - returns: True if app is launched, otherwise false
 */
func openApp(withBundleIdentifier bundleIdentifier: String) -> Bool {
    // Call the Private API LSApplicationWorkspace method
    return workspace.openApplication(withBundleID: bundleIdentifier)
}

原来的:

您所做的可能违反了iOS 人机界面指南(尽管不再专门定义“不要以编程方式退出”),因此正如评论所说,它不适合 App Store。无论如何,一旦您的应用程序以这种方式暂停,我不希望有办法以编程方式恢复它,除非您可以挂接到后台操作来运行URLSessionTask.resume,但我没有测试它并且不确定它是否可以工作.

应用程序可以通过使用自定义 URL 方案或通过推送通知以编程方式从另一个应用程序或今天的扩展程序启动(并因此进入前台)。无法通过 URL Scheme 从后台操作启动应用程序,因为它是 UIKit 框架的一部分,必须在主线程中运行。

总之,我认为您最好的选择是尝试使用通知。这只是意味着用户需要单击通知才能将您的应用程序重新置于前台。


推荐阅读