NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:currentVideoDownload];
filePath = [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[responseData writeToFile:filePath atomically:YES];
NSError *error;
NSData *mediaData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMapped error:&error];
NSLog(#"Length:%d Error:%#",[mediaData length],[error localizedDescription]);
LOG value: Length:0 Error: The operation could not be completed.
(Cocoa error 60)
Data is saving on file path properly but while fetching data from same path getting zero.
Thanks in advance.
The issue is that you are not writing to a writable file path. This is most likely because you are escaping the file path, which is not necessary, and in fact could cause IO reads/writes to fail if the escaped path does not exist. Percent escapes should only be used for HTTP requests, or related NSURL operations. Try removing the line:
filePath = [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Related
in my Code below,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localPath = [[paths objectAtIndex: 0] stringByAppendingPathComponent: #"temporary.png"];
NSLog(#"local path=%#", localPath);
[UIImagePNGRepresentation(self.scriptPicture.image) writeToFile:localPath atomically:YES];
//[opData.scripts writeToFile:localPath atomically:YES];
if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
NSLog(#"file is exist");
NSURL *fileurl=[NSURL URLWithString:localPath];
CKAsset *myfile=[[CKAsset alloc] initWithFileURL:fileurl];
//postRecrod[#"scriptPicture"]=myfile;
[postRecrod setObject:myfile forKey:#"scriptPicture"];
}
error will occur in the line of "CKAsset *myfile=[[CKAsset alloc] initWithFileURL:fileurl];"
error message is below:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Non-file URL'
I don't know how to solve this and search web all night long, but no help.
Please help me ! I am a code beginner !
You are building your fileurl incorrectly.
Replace this line:
NSURL *fileurl=[NSURL URLWithString:localPath];
with this one:
NSURL *fileurl=[NSURL fileURLWithPath:localPath];
Always use the fileURLWithPath: method to create a file URL from a file path. Use URLWithString: when creating a URL for strings that represent a proper URL starting with a scheme (such as http:, mailto:, etc.).
I think your string will start with file://
Could you try changing it to something like this:
In Swift:
CKAsset(fileURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("temporary", ofType: "png")!))
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];
I need to write a string into a file. For that, my code is:
-(void)writeToFile:(NSString *)fileName: (NSString *)data {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:appFile atomically:YES];
}
I am calling this method like this
ownServices *obj = [[ownServices alloc]init];
[obj writeToFile:#"iphone.txt" :#"this is mahesh babu"];
but it didn't write into the text file.
What's the reason? Can anyone please help me.
Thank u in advance.
The most likely problem is that the documents directory does not exist. Create it if it doesn't, then write to it:
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *parentDir = [paths objectAtIndex:0];
/* Create the parent directory.
* This is expected to fail if the directory already exists. */
(void)[[NSFileManager defaultManager]
createDirectoryAtPath:parentDir
withIntermediateDirectories:YES
attributes:nil error:NULL];
NSString *path = [parentDir stringByAppendingPathComponent:fileName];
/* Now write, and if it fails, you'll know why thanks to the |error| arg. */
NSError *error = nil;
BOOL ok = [data writeToFile:path options:NSDataWritingAtomic error:&error];
if (!ok) {
NSLog(#"%s: Failed to write to %#: %#", __func__, path, error);
}
Even simpler would be to use the latest API, which will create the directory for you if it doesn't already exist:
NSError *error = nil;
NSURL *parentURL = [[NSFileManager defaultManager]
URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask
appropriateForURL:nil create:YES error:&error];
if (!parentURL) {
NSLog(#"%s: *** Failed to get documents directory: %#", __func__, error):
return;
}
NSURL *furl = [parentURL URLByAppendingPathComponent:fileName];
error = nil;
BOOL ok = [data writeToURL:furl options:NSDataWritingAtomic error:&error];
if (!ok) {
NSLog(#"%s: *** Failed to write to %#: %#", __func__, furl, error);
}
Firstly, you are calling your method strangely. Rename the method to
-(void)writeString:(NSString *) data toFile:(NSString *)fileName
and call it like so:
[obj writeString:#"this is mahesh babu" toFile:#"iphone.txt"];
Secondly, writeToFile:atomically: is deprecated, use writeToFile:atomically:encoding:error::
NSError *error = nil;
BOOL success = [data writeToFile:appFile atomically:YES encoding:NSUTF8Encoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
This way, you also see what the error is.
Your code looks OK. Use the debugger (or an NSLog statement) to verify the values of data and appFile. If data is nil, nothing will happen (including no errors) because sending a message to nil is a no-op. It's also possible that appFile is not the path you think it is.
Check the permissions of the directory you are trying to write to (ls -la). On the device you can't, but on the simulator you can. Is it read-only for you? Is it owned by another user?
Assuming that isn't the problem, try calling with atomically:NO. Atomic file writing is performed by writing a file, then renaming it to replace the old one. If the problem is there, that will isolate the problem.
Bonus Style Critique
Class names should start with an uppercase letter: OwnServices instead of ownServices
Although your method name is perfectly valid, it's unusual to have two parameters with no words to separate them. A name like writeToFile:string: would be better.
Don't name a variable data if it is meant to point to an instance of something other than NSData. It's confusing, and there's almost a better (more specific) word you can use beside "data".
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).
I am using the following code to open a file's contents and save it to another file.
when it runs the original file length is 793 but the saved file is 0. I have also tried just to copy the file. Nothing seems to work.
Is there some kind of permissions I'm missing on the documents directory?
NSError *error;
NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* nGram = [basePath stringByAppendingPathComponent:#"contacts.gram"];
NSString *oGram = [basePath stringByAppendingPathComponent:#"/../vText.app/model/lm/TAR9230/contacts.gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:oGram encoding:NSUTF8StringEncoding error:&error];
BOOL ok = [gramString writeToFile:nGram atomically:NO encoding:NSUnicodeStringEncoding error:&error];
if(!ok) NSLog(#"Mayday!");
NSLog(#"%d",[gramString length]);
gramString = [[NSString alloc] initWithContentsOfFile:nGram encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%d",[gramString length]);
This entire block is unnecessary. All you need is:
NSString *fp=[[NSBundle mainBundle] pathForResource:#"contacts" ofType:#"gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:fp
encoding:NSUTF8StringEncoding
error:&error];
You certainly don't want to try to directly access a file in the app bundle using a hardcoded path because the file isn't guaranteed to be in the same exact place in every build.
In the code you do have, you want to use the same encoding constant for reading as you did for writing. You write with NSUnicodeStringEncoding but you read with NSUTF8StringEncoding. These should overlap but why take the chance if you know the exact coding used?