我按照上一个问题 ( Swift , Xcode, iOS - How to handle a file sent with 'Open in...' from another app to my own app ) 将函数集成到我的应用中的 Open in...
中。例如,我想使用 Files
应用程序选择一个文档文件(例如 PDF)并在我自己的应用程序中打开。
但是,AppDelegate
中的以下代码不会被调用。我想知道这是否是因为 Swift 的版本差异? Apple 是否更改了 iOS 15 或更早版本的源代码来执行此操作?如果我能听到如何在 Swift 5
、iOS 15
中实现这一点,我将不胜感激。
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool{
do {
let data = try Data(contentsOf: url)
// Do something with the file
print ("File was shared!")
print (data)
} catch {
print("Unable to load data: \(error)")
}
return true
}
我已经以其他应用可以尝试共享文件的方式设置了该应用。当尝试在我的应用程序中打开时,我的应用程序打开了,但上面的代码似乎没有被调用。
最佳答案
看来您遵循了 this previous question 中的方法仅部分。在这种情况下,此人已成功实现了自定义 URL 方案解决方案的 3 个部分中的 2 个,因此答案仅提供了第 3 部分。
如https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app说:
To support a custom URL scheme:
- Define the format for your app’s URLs.
- Register your scheme so that the system directs appropriate URLs to your app.
- Handle the URLs that your app receives.
他们的问题是:
My app is being displayed in the available applications to which I can send the file to. My question is what happens after? When I choose to send it to my app it then switches over to my app and from there, I don't know how to receive the file and read it to extract its content.
所以他们已经完成了步骤 1 和 2(因此,他们的应用程序在可用应用程序中正确显示,等等)。
就您而言,听起来您还没有完成第 1 步和第 2 步?
另一种可能性是(同样来自 https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app )如果您正在使用场景,请注意您的应用程序还有其他入口点。
If your app has opted into Scenes, and your app is not running, the system delivers the URL to the scene(:willConnectTo:options:) delegate method after launch, and to scene(:openURLContexts:) when your app opens a URL while running or suspended in memory.
类似于
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
// Determine who sent the URL.
if let urlContext = connectionOptions.urlContexts.first {
let sendingAppID = urlContext.options.sourceApplication
let url = urlContext.url
print("source application = \(sendingAppID ?? "Unknown")")
print("url = \(url)")
// Process the URL similarly to the UIApplicationDelegate example.
}
/*
*
*/
}
正如苹果文档所说,对于应用程序在后台的情况,然后实现类似的东西
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>){
let url = URLContexts.first?.url
print("url = \(url)")
// Process the URL similarly to the UIApplicationDelegate example.
}
关于ios - 如何处理从另一个应用程序共享到我自己的 iOS 应用程序的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69926336/