The operation couldn’t be completed. (Cocoa error 260.) - iphone

I'm new on IOS development and i'm working on a pdf application and i need to store a PDF file on a NSData variable, I have the PDF path but i get this message error when i try to put this pdf on the NSData variable using dataWithContentsOfFile her is my simple code :
NSError *error;
NSString *PdfPath = [NSString stringWithFormat:(#"%#"),document.fileURL ];
NSString *newPath = [PdfPath stringByReplacingOccurrencesOfString:#"file://localhost" withString:#""];
NSLog(#"OriginalPdfPath => %#", newPath);
NSData *pdfData = [NSData dataWithContentsOfFile:newPath options:NSDataReadingUncached error:&error];
NB : the pdf path is in this format : /Users/bluesettle/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/BBEF320E-7E2A-49DA-9FCF-9CFB01CC0402/ContractApp.app/Pro.iOS.Table.Views.pdf
thanks for your help

Cocoa error 260 is a NSFileReadNoSuchFileError (as listed in FoundationErrors.h), meaning the file could not be found at the path you specified.
The problem is that your path still contains encoded spaces (%20), because you're basing it on the URL. You can simply do this:
NSData *pdfData = [NSData dataWithContentsOfFile:[document.fileURL path]];

Try to use NSBundle
NSString *newPath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"pdf"]
Edit:
Than you can use bundleWithPath method, here is an example:
NSString *documentsDir= [NSString stringWithFormat:#"%#/Documents", NSHomeDirectory()];
NSString *newPath= [[NSBundle bundleWithPath:documentsDir] bundlePath];

Related

iOS - how to read entire content of an html resource file into an NSString *?

I want to put the content of my html resource file into an NSString object. Is it possible and advisable to do that? How could it be done?
Possible? - yes
Advisable? - unless it is an extremely large file, why not?
How? - There is already a method to do it for you in NSString - stringWithContentsOfFile:encoding:error:.
See the snippet below:
NSError* error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource: #"foo" ofType: #"html"];
NSString *res = [NSString stringWithContentsOfFile: path encoding:NSUTF8StringEncoding error: &error];

Get image bytes

I am trying to load the bytes of an image like this:
NSURL *img = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"img" ofType:#"png"] isDirectory:NO];
NSString * test = [NSString stringWithContentsOfFile:[img absoluteString] encoding:NSASCIIStringEncoding error:&err];
But I always get following error:
Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn\u2019t be completed.
(Cocoa error 260.)" UserInfo=0xc02abf0
{NSFilePath=file://localhost/Users/admin/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/C55551DB-152A-43D6-A1E0-9845105709D6/myApp.app/img.png,
NSUnderlyingError=0xc02ccc0 "The operation couldn\u2019t be completed. Folder or file does not exist"}
However the file DOES exist, and if I copy/paste the NSFilePath into the browser it finds the image. What could be wrong?
Why not
NSString *path = [[NSBundle mainBundle] pathforResource:#"img" ofType:"png"];
NSData *data = [NSData dataWithContentsOfFile:path];
You can't just store random bytes in an NSString - it will try to convert them into a string and might fail. You need to use an NSData object for binary data.
You also don't need to use NSURLs at all; NSBundle will give you a path as a string.
As you are using the file URL, use [img path] instead of [img absoluteString] in the second line.
Or use [NSURL URLWithPath] in the first line.
Store bytes in NSData:
NSData *bytes = UIImagePNGRepresentation([UIImage imageNamed:#"myImage.png"]);
NSData* imageData = UIImagePNGRepresentation("imagename.."); //the image is converted to bytes

Reading Image from the Local Folder in Objective C

I need to Read a Image from the specific URL .
It works fine with WWW . but it returns a nil when the URL pointing the Local Folder .
// Works
NSString *sampleData = #"http://blogs-images.forbes.com/ericsavitz/files/2011/05/apple-logo2.jpg";
// Returns nil
NSString *sampleData = #"USER/user2/...";
Note :
I am changing the NSString to NSURL and creating the UIImage .
NSURL *url = [NSURL URLWithString: data];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
You are supplying a relative pathname for the file URL. That relative pathname is interpreted relative to the current working directory of the running application, which isn't guaranteed to be anything in particular, and so is almost certainly not what you want.
You can either supply an absolute path - one that starts with '/' - or set your app's current working directory to something explicit, like your user's Documents folder.
you probably should have a look into the NSBundle Class.
Methods like
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath
or
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
is probably what you want
First of all, you can NOT read file from such path you given: "USER/user2/...", the file must in your App bundle or in your App's sandbox.
Second, check your path string if there was some texts need to be encoded in URL. Try:
NSURL *url = [NSURL URLWithString:[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Also, if the url is not nil, you should also check if your [NSData dataWithContentsOfURL:url]; is returning nil. If so, it means your URL is not correct so the method cannot find your file.
P.S., You are mistyping your image create code, you should call alloc before imageWithData:.
You should do something like to get the local url :
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, nameOfFile];
and finaly, load your image :
UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath];
Try these instead
NSString *path = #"USER/user2/.../xxx.xxx";
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isFileExist = [fileManager fileExistsAtPath:path];
UIImage *image;
if (isFileExist) {
image = [[UIImage alloc] initWithContentsOfFile:path];
}
else {
// do something.<br>
}

Store and Load File from URL

iPhone App
I am currently trying to understand how i can store a file from a URL to the documents directory and then read the file from the documents directory..
NSURL *url = [NSURL URLWithString:#"http://some.website.com/file"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:#"Timetable.ics"];
[data writeToFile:storePath atomically:TRUE];
I got this code from http://swatiardeshna.blogspot.com/2010/06/how-to-save-file-to-iphone-documents.html
I want to know if this is the correct way to do this and i want to know how i can load the file from the documents directory into an NSString..
Any help will be greatly appreciated.
What you have looks correct, to read that file back into a string use:
EDIT: (changed usedEncoding to encoding)
NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:storePath encoding:NSUTF8StringEncoding error:&error];
Of course you should change the string encoding type if you are using a specific encoding type, but UTF8 is likely correct.
If you're doing this on your main thread, then no it's not correct. Any sort of network connection should be done in the background so you don't lock up the interface. For that, you can create a new thread (NSThread, performSelectorInBackground:, NSOperation+NSOperationQueue) or schedule it on the run loop (NSURLConnection).

to print local xml file through NSData?

i want to take some xml data from local path,and to parse,but when i use following code
NSLog returns(content) different texts which is differed from xml file, how can i get exact xml data to check ,it consists correct xml data or not? any help please? when i parse , it returns nothing..i have saved the file as .xml and copied to local resource folder?
NSString *xmlFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"samp.xml"];
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath];
NSData *data = [NSData dataWithBytes:[xmlFileContents UTF8String] length:[xmlFileContents lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
NSString *content=[[NSString alloc]
initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
NSLog(#"%#",content);
This is almost assuredly an encoding problem. Make sure your xml file is in UTF8 or convert it to UTF8 before you try to create the NSData object. Once that's done, the following code produces the same output as input.
NSString *open = [NSString stringWithContentsOfFile: [#"~/Desktop/note" stringByExpandingTildeInPath] encoding: NSUTF8StringEncoding error: NULL];
NSData *data = [NSData dataWithBytes: [open UTF8String] length: [open lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
NSString *save = [NSString stringWithUTF8String: [data bytes]];
[save writeToFile: [#"~/Desktop/note2" stringByExpandingTildeInPath] atomically: NO encoding: NSUTF8StringEncoding error: NULL];
You'll probably want to use one of the NSXML classes, unless you want to do all of the parsing yourself.