Unable to read contents of .doc file in iOS - ios

I am trying to read in arabic text that I have contained inside of a .doc file, and use it in my app. Unfortunately, the only way I am able to retrieve the text is if I convert the document into .txt file.
Here is the code I have:
NSError *error = nil;
NSString *path = #"MyArabicDocument";
NSString *root = [[NSBundle mainBundle]pathForResource:path ofType:#"doc"];
NSString *myFile = [NSString stringWithContentsOfFile:root encoding:NSUTF8StringEncoding error:&error];
NSLog(#"my file contents are: %#", myFile);
NSLog(#"error is: %#", error);
The output of my NSString object is (null), and the error I get is:
error is: Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x7aace470 {NSFilePath=/Users/MyName/Library/Developer/CoreSimulator/Devices/.../data/Containers/Bundle/Application/..MyApp.app/MyArabicDocument.doc}
If I convert my document into an .rtf format, then my output (after changing the extension in the above block of code) is the following:
my file contents are: {\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
{\fonttbl\f0\fnil\fcharset0 LucidaGrande;\f1\fnil\fcharset178 AlBayan;\f2\fnil\fcharset178 GeezaPro;
}
{\colortbl;\red255\green255\blue255;}
\vieww10800\viewh8400\viewkind0
\deftab709
\pard\pardeftab709\pardirnatural
\f0\fs46 \cf0 1
\f1 - \'de\'f3\'dc\'c7\'e1\'f3 \'c7\'c8\'fa\'dc\'e4\'f5 \'c2\'c8\'f3\'f8 \'e6\'f3\'c7\'d3\'fa\'e3\'f5\'dc\'e5\'f5 \'e3\'f5\'cd\'f3\'e3\'f3\'f8\'dc\'cf\'f5
\f0 ~~~
\f1 \'c7\'e1\'e1\'e5\'f3 \'dd\'f6\'dc\'ed \'df\'f5\'dc\'e1\'f6\'f8 \'c7\'e1\'c3\'f5\'e3\'f5\'dc\'e6\'d1\'f6 \'c3\'f3\'cd\'fa\'dc\'e3\'f3\'dc\'cf\'f5 \
...
If I try to use an NSAttributedString object instead of an NSString object, but I still get a (null) value for my NSAttributedString object:
NSDictionary *attrs = #{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType, NSWritingDirectionAttributeName:#[#(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]};
NSAttributedString *text = [[NSAttributedString alloc] initWithFileURL:[[NSBundle mainBundle] URLForResource:#"MyArabicDocument" withExtension:#"doc"] options:attrs documentAttributes:nil error:&error];
The reason why this is important is that while my arabic text does indeed appear in my UITextView in my app, the problem is that it's appearance is nowhere near as nice as in the original document, which is what I would like to maintain in my app. Is this not possible?

.doc file in question is in binary format. (probably compressed like .docx)
http://en.wikipedia.org/wiki/Doc_(computing)
So you cannot put it in NSString as is. But you can get NSData:
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyArabicDocument" ofType:#"doc"];
NSData *data = [NSData dataWithContentsOfFile:path];
Unfortunately you cannot make an NSAttributedString from .doc in iOS, but you can in OS X (in iOS there only four doc types supported)
NSError *attrError;
NSDictionary *options = #{NSDocumentTypeDocumentAttribute: NSDocFormatTextDocumentType};
NSAttributedString *content = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:&attrError];
Instead you may try to load your .doc file into WebView.
Using NSData:
[self.webView loadData:data MIMEType:#"application/msword" textEncodingName:#"UTF-8" baseURL:nil];
But I think better with NSURLRequest (since you don't nee to set up encoding there)
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
NOTE: Any method you choose very likely will BREAK your format, I mean rendered document will be corrupted. Instead I recommend to convert .doc to .pdf In this case it will be good-loking.
For example Dropbox app for iOS defenetly converts .doc/.docx to pdf and than presented to the user as PDF (Of course not telling that it is PDF indeed).

I think you have a encoding issue when reading a file,
Refer below link
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/readingFiles.html
May be it solve your problem
Best of luck!

Related

iOS: Some files don't open

I am attempting to load image files as an NSString, but all of them come up nil using this code:
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:name.data()] ofType:nil];
NSString *da = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
I am able to load many files, but all JPEG and PNG files fail for some reason. I thought it might have something to do with encoding so I switched it to usedEncoding, but it still didn't work.
What am I missing?
EDIT:
I have been making an iOS/Android cross platform OpenGL graphics library in C++. Everything works except texture loading. Any file loading from disk goes through one function that is abstracted between systems. I need the image file in an STL string, so that I can pass it to an image parsing library to get the raw pixel data.
I just think that it's reduculous that the function I have can open any file except images.
If you run your code, passing an NSError instance instead of nil,
NSError *error = nil;
NSString *string = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
you will see that stringWithContentsOfFile cannot open the image file, returning nil and the error given is:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)"...
Cocoa error 261 is NSFileReadInapplicableStringEncodingError which means the encoding of the file is different from the one you are passing (NSUTF8StringEncoding). But I have tried with the other encodings, and none works for PNG files.
You can still achieve what you want by loading the file as a UIImage and then converting the UIImage into a Base64 string.
Since iOS 7, this is easier because you can use the built in method base64EncodedStringWithOptions:
// Load the image and convert it to NSData
UIImage *image = [UIImage imageNamed:#"yourImageName"];
NSData *imageData = UIImagePNGRepresentation(image);
// You can use the equivalent UIImageJPEGRepresentation() for JPEG images
// Convert NSData to a Base64 NSString
NSString *base64ImageString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
Previous to iOS 7, you can do the exact same thing but you will have to implement your own Base64 encoding method (Or import any of the many already available, eg. nicklockwood/Base64).

Initializing NSAttributedString with HTML file parses HTTP links as file URLs

iOS 7 allows an NSAttributedString to be initialized with an HTML file or data. I want to use this functionality to make it easier to insert links in 'About' texts of apps.
To achieve this, I initialize the NSAttributedString with the following code:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"test.html" withExtension:nil];
NSError *error = nil;
NSDictionary *options = nil;
NSDictionary *attributes = nil;
_textView.attributedText = [[NSAttributedString alloc] initWithFileURL:url options:options documentAttributes:&attributes error:&error];
and a file with the following content:
<html><body>
<p>This is a test link. It leads to StackOverflow.<p>
</body></html>
Update
The above HTML still had the escape marks from trying to use it in code as an NSString. Removing the escapes makes it work just fine. Also answered my own question below.
End update
This works fine, and gives a string with the url properly formatted and clickable. Clicking the link calls the UITextView's delegate -textView:shouldInteractWithURL:inRange: method. However, inspecting the URL parameter shows the URL actually has the following absolute string:
file:///%22http://www.google.com/%22
which obviously doesn't open the appropriate webpage. I don't find the documentation on NSAttributedText clear enough to determine why this happens.
Anyone know how I should initialize the NSAttributedString to generate the appropriate URL?
Try reading the HTML file into a NSString and then use:
NSString *path = [[NSBundle mainBundle] pathForResource:#"test.html" ofType:nil];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
_textView.attributedText = [[NSAttributedString alloc] initWithHTML:html baseURL:nil options:options documentAttributes:&attributes];
At least this should work if it is similar with what happens in UIWebViews. The URL is resolved using the baseURL. It appears that in your code the source url is also used as baseURL. So I am passing a nil URL to prevent resolving against a local file URL.
The answer to this question is that the HTML file was invalid.
Having copy/pasted the html directly from a string defined in Objective-C, I forgot to remove the escapes before each quote. This of course translated directly to a file url instead of an HTML url. Removing the escape marks fixes this.

iOS 6 - Able to save .pdf from URL, able to display it in a WebView, NOT able to move it to iBooks

This is what I'm trying to do:
Get a .pdf from external URL
Save it into my local disk
Display it in a WebView
Allow the user to move the .pdf to another app who can read .pdf
Everything from 1 to 3 works fine. But nothing is moved/shared to/with other apps. I can't understand what I'm doing wrong. This is what I'm doing.
How I save the pdf in the Documents folder (viewDidLoad):
// to save the pdf into local file system (tempString is the pdf url)
NSData *pdfData = [[NSData alloc]
initWithContentsOfURL:[NSURL URLWithString:tempString]];
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePAth atomically:YES];
// to populate the WebView
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[my_web_view setUserInteractionEnabled:YES];
//[editoriale_view setDelegate:self];
[my_web_view loadRequest:requestObj];
In my viewDidLoad() function I create a button to allow the user to open a list of apps who can read .pdf files:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self
action:#selector(show_Button)];
And here's my show_Button function:
-(void)show_Button {
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath
stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
When I try this on my device everything works fine until I tap on one of the icons in the list (i.e. the iBooks one). Then the app closes (it doesn't crash, it simply closes).
Here's what the console prints for the two logs I put in the show_Button function:
1. filePath = /Users/[MY_USER]/Library/Application Support/iPhone
Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
2. url2 = file://localhost/Users/[MY_USER]/Library/Application%20Support/
iPhone%20Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
Anyone wants to try to make me understand what I'm doing wrong? I'm using Xcode 4.6. I browsed my iPhone app file system with a third-party software and the file "MyPDF.pdf" actually IS in the Documents" folder, and that's clear because the WebView is correctly populated.
Change CGRectZero to self.view.bounds when you display the document controller.
Solved. I had not implemented the UIDocumentenInteractionController delegate in the .h file. Now I have and everything works fine. Thank you to #trojanfoe for the useful hint.

Open in iBook a PDF with spaces in the name

I've implemented the already nth-times discussed open in iBook feature in my PDF viewer. And it works great when the PDF file does not contain spaces (example1.pdf, example2.pdf). When the PDF has some space (example 1.pdf) in the name clicking the open in iBook button does nothing.
NSString *fileURL = [(Documents *)(self.detailItem) url];
NSArray *subStrings = [fileURL componentsSeparatedByString:#"/"];
NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:[subStrings lastObject]];
docIntController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
docIntController.delegate = self;
docIntController.UTI = #"com.adobe.pdf";
[docIntController presentOptionsMenuFromBarButtonItem:sender animated:YES];
Any suggestion is welcomed. Thanks :)
Since the filePath string is intended to be a URL, you likely need to run it through NSString -stringByAddingPercentEscapesUsingEncoding: before invoking fileURLWithPath:
Try enclosing the full path that you send to iBooks in quotes.
For example, use "example 1.pdf" instead of example1.pdf.

iOS development - WebPage SourceCode

Is there a url (.txt) for the source code of each website?
If not, how can i get the source code of a webpage and be able to show it in a UITextView ?
You should be able to use something like this:
NSString *googleString = #"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL
encoding:NSASCIIStringEncoding
error:&error];
This will put the contents of the google home page into googlePage and, if applicable, the error into error. If the page being loaded uses Unicode characters, try NSUTF8StringEncoding instead of NSASCIIStringEncoding.

Resources