1

I'm unable to open a local file in Safari using Swift's openUrl() function which keeps returning false:

let url = URL(string:"file:///Users/kiwitech/Library/Developer/CoreSimulator/Devices/FFA6761D-D98B-4C41-ACEF-18249F297897/data/Containers/Data/Application/82EF4E60-F9E9-434B-B86B-0391052D1E6E/Documents/proposals_dataxlsx.xlsx");

print("Local URL",url)
if UIApplication.shared.canOpenURL(url!) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url!, options: [:],completionHandler: {
            (success) in
            print("Open  \(success)")
        })
    } else {
        UIApplication.shared.openURL(url!)
    }
}
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
  • Im not sure if you can open a local file of another app on Safari. Why no open in in an UIWebView or WKWebView instead? – koropok Dec 21 '17 at 10:02

2 Answers2

0

To load File urls, you should use Data(contentsOf: url), but if you want to open it you should use UIDocumentInteractionController instead.

Jacob
  • 77,566
  • 24
  • 149
  • 228
0

That's is correct only. find the canopenURL: definition.

Returns a Boolean value indicating whether or not the URL’s scheme can be handled by some app installed on the device.

It means that whenever you query for canOpenURL:(), iOS will see if any of the installed apps are registered for the scheme that you are requesting, If it couldn't able to find anything, then it will return false..

As the returning URL does not have any scheme attached to it, canOpenURL will return false. If you want to open a URL in Safari, it should start with http:// or https://, these are schemes registered for Safari.

One more thing is that, for canOpenURL(:), to work properly you need to whitelist the schemes. you can find more about this here. https://developer.apple.com/documentation/uikit/uiapplication/1622952-canopenurl

If you have registered custom schemes, then the respective app will open when you hit open(url).

one more thing, never hard code like the below.

let url = URL(string:"file:///Users/kiwitech/Library/Developer/CoreSimulator/Devices/FFA6761D-D98B-4C41-ACEF-18249F297897/data/Containers/Data/Application/82EF4E60-F9E9-434B-B86B-0391052D1E6E/Documents/proposals_dataxlsx.xlsx");

use NSSearchPathForDirectoriesInDomains, to create or search for a file in the directories.

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"New Folder"];
Kumar Reddy
  • 792
  • 6
  • 15