Nikita P
Nikita P

Reputation: 4246

OpenURL to a file in NSBundle

I have a file, which i want to open in safari (or call it view in safari). I add this file to my bundle resources.

and do the following:

NSString *path = [[NSBundle mainBundle] pathForResource:@"tryFile.txt" ofType:nil inDirectory:nil];
NSURL *url = [NSURL fileURLWithPath: path];
NSLog(@"path: %@ \n url:%@ \n can open url:%d",path,url,[[UIApplication sharedApplication] canOpenURL:url]);
BOOL didGo = [[UIApplication sharedApplication] openURL:url];
NSLog(@"didgo?: %d",didGo);

Of course, as the sandboxed environment says, I am not able to open the file ins safari. It says, canOpenURL as yes but then didGo is NO.

How can I do this without setting up a local server. Please suggest. Should I keep the data stored in a variable and then open an html page with that data...or what?

EDIT: These are the logs:

path: /var/mobile/Applications/C78C7CD8-22C7-468A-AA5D-AF22C6042378/TryApp.app/tryFile.txt 
url:file://localhost/var/mobile/Applications/C78C7CD8-22C7-468A-AA5D-AF22C6042378/TryApp.app/tryFile.txt 
can open url:1



didgo?: 0

PLEASE NOTE opening the file in a webview is not an option. The requirement wants it to be opened in safari. And anyways, this example is of a text file...the filethat may be opened can be anything, and webview does not support all file types.

Upvotes: 0

Views: 2004

Answers (3)

D.M Patel
D.M Patel

Reputation: 145

 NSString *path = [[NSBundle mainBundle] pathForResource:@"tryFile.txt" ofType:nil inDirectory:nil];

 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:path]];

This code is for open url in directly in safari OR you can use Webview and direct open url in your webview.thanks

Upvotes: 0

Amar
Amar

Reputation: 13222

The txt file resides within your application sandbox. The URL that you are trying to load in Safari will not get loaded due to security in iOS. Read more about it here
As a workaround you can use a UIWebView in your application and open the file in that.

Cheers!
Amar.

Upvotes: 2

Wain
Wain

Reputation: 119041

You'll need to setup a server or open the page in a UIWebView inside the app.

Upvotes: 0

Related Questions