open file from local file system with default application iOS

前端 未结 1 1020
盖世英雄少女心
盖世英雄少女心 2021-02-06 14:05

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 applica

相关标签:
1条回答
  • 2021-02-06 14:28

    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];
    

    Finally if the above line returns yes then open the resource.

    if (canOpenResource) { [[UIApplication sharedApplication] openURL:resourceToOpen]; }
    

    I quote the following from UIApplication class reference with respect to the instance method canOpenURL:

    This method guarantees that that if openURL: is called, another app will be launched to handle it. It does not guarantee that the full URL is valid.

    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];
    

    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.

    0 讨论(0)
提交回复
热议问题