我正在开发一个带有操作扩展的 iOS 应用程序,我在 iOS 18 中遇到了一个关键问题。从扩展打开主应用程序的功能在 iOS 17 及更早版本中不再起作用。 iOS 18.
private func restore() {
let publicURL = String(kUTTypeURL)
let publicText = String(kUTTypeText)
let extensionItem: NSExtensionItem = extensionContext?.inputItems.first as! NSExtensionItem
let itemProvider = extensionItem.attachments?.first as! NSItemProvider
if itemProvider.hasItemConformingToTypeIdentifier(publicURL) {
itemProvider.loadItem(forTypeIdentifier: publicURL, options: nil, completionHandler: { [weak self] item, _ in
if let fileURL: NSURL = item as? NSURL,
let tmpURL = VPRealmManager.restore(url: fileURL as URL)
{
let sharedDefaults = UserDefaults(suiteName: Key.AppGroup.Identifier)!
sharedDefaults.set(tmpURL.absoluteString, forKey: "backup_file_key") // そのページのURL保存
sharedDefaults.synchronize()
self?.openVoicepaperApp(path: "restore")
}
})
}
closeExtension()
}
func openVoicepaperApp(path: String = "") {
let url = NSURL(string: "voicepaper2://" + path)
let selectorOpenURL = sel_registerName("openURL:")
let context = NSExtensionContext()
context.open(url! as URL, completionHandler: nil)
var responder = self as UIResponder?
while responder != nil {
if responder?.responds(to: selectorOpenURL) == true {
responder?.perform(selectorOpenURL, with: url)
}
responder = responder!.next
}
}
func openVoicepaperApp(path: String = "") {
if let url = URL(string: "voicepaper2://" + path) {
extensionContext?.open(url, completionHandler: nil)
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// ... other URL handling logic ...
let DefaultsForAppGroup = UserDefaults(suiteName: Key.AppGroup.Identifier)!
if url.absoluteString.contains("restore"), let fileUrl = DefaultsForAppGroup.object(forKey: "backup_file_key") as? String,
let backupFileURL = URL(string: fileUrl)
{
// Show alert and perform restore
}
return true
}
操作扩展中
openVoicepaperApp
的两种实现都无法在iOS 18中打开主应用程序,而它们都可以在iOS 17及更早版本中运行。这会阻止恢复过程在 iOS 18 中启动。
任何见解、建议或替代方法将不胜感激。谢谢!
我遇到了类似的问题,但我找到了一种方法来确保在 iOS 18 上可以从扩展程序打开主应用程序。以下是您可以使用的简单实现:
/// Redirect To App
func redirectToApp() {
let urlString = "Your URL"
guard let redirectionURL = URL(string: urlString) else {
return
}
print("Redirecting to URL: \(urlString)")
openURL(redirectionURL)
}
/// Open URL Code
@objc @discardableResult func openURL(_ url: URL) -> Bool {
var responder: UIResponder? = self
while responder != nil {
if let application = responder as? UIApplication {
if #available(iOS 18.0, *) {
application.open(url, options: [:], completionHandler: nil)
return true
} else {
return application.perform(#selector(openURL(_:)), with: url) != nil
}
}
responder = responder?.next
}
return false
}