how to open file.xlsx in UIWebView IOS using objective-c - ios

I have file.xlsx in my IOS app documents folder. I want to show open this excel file in UIWebview. but i am getting below error,
Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted"
but pdf and CSV files are opening,
I am new to IOS and tried all possible things for it to work i guess from last 2 days. nothing worked out.. please help me
Update: Even if i rename it as file.xls its not opening
below is my code,
NSURL* nsUrl = [NSURL URLWithString:url];
_urlReq = [NSURL URLWithString:url];
[self performSelector:#selector(urlRequestForFile) withObject:nil afterDelay:0];
_webView.delegate = self;
NSURLRequest* request = [NSURLRequest requestWithURL: nsUrl];
[_webView loadRequest: request];
-(void)urlRequestForFile{
self.connection = nil;
NSURLRequest *requestForFile = [NSURLRequest requestWithURL:_urlReq cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:300];
_connection = [[NSURLConnection alloc]initWithRequest:requestForFile delegate:self startImmediately:YES];
_ongingServiceFlag = YES;
}
need help in showing xlsx file inside my IOS app either using UIWebView or is there any other way to show xlsx file inside the app without using third party apps?
Update(Solution):
I am very surprised to see that there is no support for XLSX mentioned even in apple site for UIWebView but actually UIWebView completely supports XLSX format. one thing you need to make sure is to specify the correct 'textEncodingName' value. if your file is stored with base64 binary encoding u have to mention it as textEncodingName:#"base64" otherwise u have to mention as "utf-8"
Below line worked for me:
[webView loadData:urlData MIMEType:#"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" textEncodingName:#"base64" baseURL:nil];

Use QLPreviewController for showing xlsx document in your app. Find the links for the tutorial below.
https://developer.apple.com/documentation/quicklook/qlpreviewcontroller
http://iosdevelopertips.com/data-file-management/preview-documents-with-qlpreviewcontroller.html
https://www.appcoda.com/quick-look-framework/

The .XLSX filetype is based on openXML which is good news! This means it's easily readable, we just need to let the webview know the type, or rather mimeTYPE, of the file we are loading/displaying. According to microsoft the mimetype to use for XLSX (OpenXML) files is:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
source: https://blogs.msdn.microsoft.com/dmahugh/2006/08/08/content-types-for-open-xml-documents/
To do this we load the data (dataWithContentsOfFile: or dataWithContentsOfURL: or your prefered method) by calling the webView method:
[_webView loadData:<#(nonnull NSData *)#> MIMEType:<#(nonnull NSString *)#> textEncodingName:<#(nonnull NSString *)#> baseURL:<#(nonnull NSURL *)#>]
Example of my working code:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://mycoolserver.com/file.xlsx"]];
[_webView loadData:data MIMEType:#"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" textEncodingName:#"utf-8" baseURL:nil];

.xlsx File cannot be opened using UIWebView. Though you can load .xls file using UIWebView.
Here is a list of files which you can load using UIWebView
https://developer.apple.com/library/content/qa/qa1630/_index.html
If you want to use .xlsx file, you have to use QuickLook FrameWork which contains QLPreviewController. Your code should be like this -
- (void) initQlController{
QLPreviewController *prev = [[QLPreviewController alloc]init];
prev.delegate = self;
prev.dataSource = self;
[self presentModalViewController:prev animated:YES];
[prev.navigationItem setRightBarButtonItem:nil]; }
Then you have to use the dataSource methods for the same : -
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller

Related

Webview loading weburl show replaced images from one place to another

I am using UIWebview to load a weburl, which contains few images and text. But after loading the url on webview images gets replaced with one another on some devices.
Is it problem with webpage?
My Code is here
NSURL *url=[[NSURL alloc]initWithString:_url];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
I have attach link to the actual loaded webview.
this image actually appears to some other location but right now it gets loaded to this place
Try to this one , it may help you..!!
https://github.com/AdrianFlorian/AFImageViewer
Images url are old, please replace with other like:
#image url: http://www.citi.io/wp-content/uploads/2015/10/1291-01-bruges-meteoweb.eu_.jpg
-(NSArray *)imageUrls
{
return [NSArray arrayWithObjects:
[NSURL URLWithString:#"http://imgs.mi9.com/uploads/landscape/4717/free-the-seaside-landscape-of-maldives-wallpaper_422_84903.jpg"],
[NSURL URLWithString:#"http://pics4.city-data.com/cpicc/cfiles42848.jpg"],
nil];
}

iOS view PDF from a given url inside of an app

I want to open and show a pdf file from a given url (somewhere in the internet) and view it in my iOS application. Could you please tell me what are the possible approaches to this problem, and list their advantages and disadvantages / limitations? I've heard about UIWebView, are there any other options?
My suggestion is using the webview.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSURL *url = [NSURL URLWithString:#"https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:request];
}
If you want to more information please refer the follwing link as well
https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html

Docx support in UIWebview(iOS)?

I have checked the official links for doc support, and it's clear that docx is not supported in UIWebview.
But, I also found out that some guys were able to open docx files in UIWebview:
Cannot open docx file through webbrowser in app using OpenIn functionality
Why doc and docx losing style information in iOS?
How to open Microsoft Office documents in iPhone
Also, afaik, iOS safari browser is built upon UIWebview and I am able to open docx files from internet in the browser.
However, when I download a docx from my test server (I have cross checked the downloaded docx by importing it from simulator and it opens perfectly on my mac), I am unable to view it in UIWebview.
I am confused,
Is docx Supported or not?
Or it seems that docx has further variety of formats out which some are supported?
Here is my loading code:
NSURLRequest *request = [NSURLRequest requestWithURL:urlPath];
[webViewForDocsView loadRequest:request];
Yes UIWebView supports the docx. Just tried loading a docx file from bundle and it seems working fine(in this example named "DOC1.docx")::
NSString *path = [[NSBundle mainBundle] pathForResource:#"DOC1" ofType:#"docx"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[mywebView loadRequest:request];
and If you are trying to display a docx file residing on a server somewhere, you can simply load it to your web view directly:
NSURL *targetURL = [NSURL URLWithString:#"http://www.central.wa.edu.au/Current_Students/JobsCareersandLeavingCentral/Documents/Resume%20Template.docx"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[mywebView loadRequest:request];
Don't know why but using the URL scheme to load docx didn't work, (below code didn't work)
NSURLRequest *request = [NSURLRequest requestWithURL:urlPath];
[webViewForDocsView loadRequest:request];
Instead, loading the file in memory(using NSData) and loading the data with MIME type worked (the below code worked like charm!)
NSString *path = [urlFileInView path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
webViewForDocsView.delegate = self;
[webViewForDocsView loadData:data MIMEType:#"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:#"UTF-8" baseURL:nil];
Using UIWebView to display select document types
As per the Apple documentation, docx isn't supported by UIWebView and is deprecated.
To open docx in app use UIDocumentInteractionController.
DispatchQueue.main.async {
let docOpener = UIDocumentInteractionController.init(url: fileURL)
docOpener.delegate = self
docOpener.presentPreview(animated: true)
}

UIWebView Delegates Not Triggering ? iOS

I am loading a local HTML into a UIWebView as follows :
- (void)viewDidLoad
{
[super viewDidLoad];
//Setup our UIWebView
webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.delegate = self;
webView.scalesPageToFit = YES;
webView.userInteractionEnabled = YES;
[self.view addSubview:webView];
...
[self loadWebPage];
}
- (void)loadWebPage {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
}
And in the header :
#interface ViewController : UIViewController <UIWebViewDelegate>
However for some reason my webview delegates are not being called :
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"Starting HTML Load Process");
}
- (void)webViewDidFinishLoad:(UIWebView *)webViewRef {
NSLog(#"Web View Finished Loading Method");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Error loading HTML ! %#", error);
}
Can anyone suggest why ?
Thanks !
Called the method [self loadWeb];
But on definition the method is - (void)loadWebPage;
Is it typo?
The only way I can reproduce is this by declaring the webView #property as weak. Can you confirm you are declaring it as a strong reference?
how did you declare your UIWebView instance variable, as a strong or weak? If weak make it strong.
The problem is that this call.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]];
Looks like you're loading the HTML from inside your bundle. This means you need to confirm that all the additional files (.js, .css, and any media files) also need to be present in your bundle.
So the first thing need to check fileURLWithPath: point either it's returning nil or not. If it's not then it means that .html page resolved, however the additional files not resolved as part of the request because it's not placed on the same "index.html" path.
First you need to confirm the directory structure of your "index.html" and all the additional files used inside the page. In order to do that, you have to right click on binary .app in your "build" directory in the finder and then select "Show Package contents".
binary (.app) > right click > Show Package contents
This shows what the app's main bundle contains. Look inside for your HTML file. If it's in a folder, that folder name needs to be in the inDirectory parameter of the pathForResource call. If it's on the top-level then you don't have a folder reference. Either delete & re-drag it into project or use the pathForResource version without inDirectory.
The best way to don't setup the base path or relative path for the resources inside .html page (.js, .css and images) because it don't work. Copy all the additional resources next to "index.html" file so it would be easy to resolve on runtime from bundle.
NSString *path = #"<Index.html Path>";
NSURL *url = [NSURL URLWithString: [path lastPathComponent]
relativeToURL: [NSURL fileURLWithPath: [path stringByDeletingLastPathComponent]
isDirectory: YES]];
Try this
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]isDirectory:NO];

Run HTML5/CSS3 in UIWebView

I've a problem that i couldn't solve, i wanna run the Apple - HTML5 Showcase - Gallary
in UIWebView inside my ipad app.
I've tried a local html file:
NSString *strr = [[NSBundle mainBundle] pathForResource:#"photo-gallery" ofType:#"html"];
NSString *str = [[NSString alloc] initWithContentsOfFile:strr encoding:NSASCIIStringEncoding error:nil];
NSLog(#"%#",str);
[webView loadHTMLString:str baseURL:nil];
and also a server html file, but it didn't work, can anyone help me, i wanna show an html5/css3 in UIWebView.
thx in advance.
hi this is what you can do
UIWebView *aWebView = [[UIWebView alloc] initWithFrame:webFrame];
//getthe path of the local html file
NSURL *baseURL = [NSURL fileURLWithPath:fileNamePath];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:baseURL];
//load the html file into the web view.
[aWebView loadRequest:aRequest];
//add the web view to the content view
[view addSubview:aWebView];
For server html you simply skip the second line, and put the address.
Hope it helps
You can take a look at phonegap. Its a complete framework for building html5 apps inside a UIWebview with native capabilities.
See: http://www.phonegap.com

Resources