问题描述
我从服务器下载了一些文件并存储到本地文件系统中。我想在设备中使用默认应用程序打开它们。如何使用默认应用程序打开文件。请提供一些示例代码。
I have downloaded some files from server and stored into local file system. I want to open them with default application in the device. How can I open files with default application. Please provide some sample code.
谢谢
推荐答案
首先你需要使用NSURL对象表示资源(要打开的文件)。
以下假设一个名为filePath的NSString已初始化,并打开了资源的路径。
First you need to represent the resource (downloaded file to be opened) with an NSURL object.The following assumes an NSString named filePath that is already initialised with the path to the resource to open.
NSURL *resourceToOpen = [NSURL fileURLWithPath:filePath];
然后最好先检查是否有应用程序打开资源。
Then it's best to check first that there is an app that will open the resource.
BOOL canOpenResource = [[UIApplication sharedApplication] canOpenURL:resourceToOpen];
最后,如果上面的行返回yes,则打开资源。
Finally if the above line returns yes then open the resource.
if (canOpenResource) { [[UIApplication sharedApplication] openURL:resourceToOpen]; }
我引用了UIApplication类引用中关于实例方法canOpenURL的以下内容:
I quote the following from UIApplication class reference with respect to the instance method canOpenURL:
但是,如果您希望向用户显示具有的应用列表使用适当的UTI注册该文件类型,你可以这样做 -
However, if your wish to present the user with a list of apps that have registered with the appropriate UTI for that file type you can do something like this-
UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
documentController.delegate = self;
[documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
您必须实现UIDocumentInteractionControllerDelegate协议。同样对于已知的文件类型,系统应解析UTI属性的正确分配而不进行设置。
You must implement the UIDocumentInteractionControllerDelegate protocol. Also for known file types the system should resolve the correct assignment of the UTI property without setting it.
这篇关于使用默认应用程序iOS从本地文件系统打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!