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")!))
Related
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];
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];
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 had some problems after starting a new coredata project with the xcode 3.2.5... my previous projects with core data (in previous xcode) worked fine, so I dont know what is the difference??
so the error I get when I build and go to the view that calls the core data is>
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
the strange thing is that in my *AppDelegate.m, in (edited thanks Rog but still not working!)
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"staff.sqlite"];
NSURL *storeUrl = [NSURL fileURLWithPath:storePath]; //new position for the storeUrl!
// Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:#"staff" ofType:#"sqlite"];
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}
}
in the
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"staff.sqlite"];
I get the warning
NSURL may not respond to '-stringByAppendingPathComponent'
I option + click this stringByAppendingPathComponent and get (Symbol not found!!!!)
but in other projects I do option + click in the same and get the definition!!
so is this warning related to my error??
how to fix it???
Edit,
included this in my viewDidLoad
NSLog(#"path= %#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]) ;
which gives me in console:
path= /Users/mkss9/Library/Application Support/iPhone Simulator/4.2/Applications/2F364C20-2B87-4ABB-AA3E-FB6F7C15096F/Documents
please!, Im getting crazy !!
thank you!
Some SDK Version ago (I don't know for sure when they did) apple changed the return type of applicationDocumentsDirectory in their project templates.
When you create a new project it looks like this:
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
in older templates it looked like this:
/**
Returns the path to the application's documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
and in between those two it looked like this:
/**
Returns the path to the application's Documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
So you have to be careful, because all the old code that relies on applicationDocumentsDirectory returning a NSString won't work with newer templates.
And you can't just replace the new version with the older version because this would result in a change in your core data methods.
So I would suggest you to write your own method for returning the documents directory. Apple changes their applicationDocumentsDirectory quite often.
I would imagine it's because -applicationDocumentsDirectory returns an NSURL * instead of an NSString *.
Firstly you need to make sure you applicationDocumentsDirectory method is returning a NSString.
Once that's out of the way, the subsequent crash is because you are passing a path and filename that don't exist yet.
So if you move your NSURL *storeUrl = [NSURL fileURLWithPath:storePath]; to after the code that checks for an existing file and puts a default one in case it doesn't exist, it should solve your problem.
I am reading a file in iphone app. Its Works Fine.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"%#",documentsDirectory);
NSString *fileName = [NSString stringWithFormat:#"%#/test.txt",documentsDirectory];
NSLog(#"%#",fileName);
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
NSLog (#"%#",content);
}
works good when i am using filename as test.txt
But when i add another file in the resource suppose test1.txt then NSLog(#"%#",documentsDirectory) and NSLog(#"%#",fileName) shows the right result. But
NSLog (#"%#",content); prints null in the log. So what is the reason?
I am printing detail error and it prints
NSFilePath = "/Users/sam-xxx/Library/Application Support/iPhone Simulator/3.2/Applications/51197946-6042-4A90-AA39-F07F8A649308/Documents/test1.txt";
NSUnderlyingError = Error Domain=NSPOSIXErrorDomain Code=2 "Operation could not be completed. No such file or directory";
It would be best here to check to see if an error is returned:
NSError *error;
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error: &error];
if (error) NSLog(#"Error !: %#", [error localizedDescription]);
That will (hopefully) give you a clue as to whats going on.
(Edited to give example bundle resource usage as the file is in the bundle not the Documents directory).
Docs for NSBundle are here: NSBundle Documentation
You have 2 choices, the one you suggest:
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
Which will return the Bundle resource directory with the filename appended to that path.
Personally I prefer the pathForResource:ofType: method:
NSString *filename = [[NSBundle mainBundle] pathForResource: #"test1" ofType: #"txt"];
As this will not only tell you if the file exists (returns nil if it does not) but will also search the localisation directories if you have them.
Did you check if the file in the error message exists? When run in the simulator you can simply open Finder, press cmd+shift+g and paste the directory to the file.
Maybe you didn't add it to the target? Open the information window for the file in your resources and check which targets are checked.
When you run a app in Simulator, you could copy and paste the right file into the app's Documents directory use Finder, but on iPhone or iTouch how could you paste a file into the Documents directory.
We got only 2 method to put something into Documents directory when app is running on iPhone or iTouch.
Create one.
Copy one from the bundle.
in your code, you read a file in the Documents directory, you could be paste a file in the directory manually use Finder. Try this.
NSString *path = [[NSBundle mainBundle] pathForResource:#"test.txt" ofType:nil];
NSString *content = [[NSString alloc] initWithContentsOfFile:path
usedEncoding:nil
error:nil];
NSLog (#"%#",content);