In my app I've to create a csv file, so I create this method:
+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
NSMutableString *target = [#"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];
for (NSDictionary *dict in promoArray) {
[target appendFormat:#"%#,%#,%#,%#,%#,%#,%#,%#\n",dict[#"name"],dict[#"surname"],dict[#"email"],dict[#"birthdate"],dict[#"address"],dict[#"city"],dict[#"zip"],dict[#"phone"]];
}
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"profiles.csv"];
NSURL *url = [NSURL URLWithString:fileName];
BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Errore: %#", error.localizedDescription);
}
}
But when I run the app, for now it saves the .plist file but it doesn't save the .csv file. When I look at the console it tells me: Error: The operation couldn’t be completed. (Cocoa error 514.). So I searched in the web what means error 514, I found this, in which I searched for the error and I found NSFileWriteInvalidFileNameError = 514, how I can solve this error? In my method what's the problem.
I hope you can help me to solve this issue
SOLVED BY MYSELF:
+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
NSMutableString *target = [#"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];
for (NSDictionary *dict in promoArray) {
[target appendFormat:#"%#,%#,%#,%#,%#,%#,%#,%#\n",dict[#"name"],dict[#"surname"],dict[#"email"],dict[#"birthdate"],dict[#"address"],dict[#"city"],dict[#"zip"],dict[#"phone"]];
}
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"profiles.csv"];
BOOL success = [target writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Errore: %#", error.localizedDescription);
}
}
Change this line
BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];
to
BOOL success = [target writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];
Related
Once plist is created data storing start automatically, but after some time it automatically stop storing data in plist. But once when i kill app and restart again, it will start again as previously mention and cycle goes on...
Here is my code
- (void)saveLocationsToPlist:(NSMutableDictionary*)mdictPlist {
NSString *plistName = [NSString stringWithFormat:#"LocationArray.plist"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [NSString stringWithFormat:#"%#/%#", docDir, plistName];
NSMutableDictionary *savedProfile = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
NSLog(#"ADD LOCATION TIME : %#",[NSDate date]);
NSLog(#"ADD LOCATION DATA : %#",mdictPlist);
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
BFLog(#"applicationDocumentsDir Not exists");
fullPath = [docDir stringByAppendingPathComponent: [NSString stringWithFormat:#"LocationArray.plist"] ];
}
if (!savedProfile) {
savedProfile = [[NSMutableDictionary alloc] init];
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
} else {
self.myLocationArrayInPlist = [savedProfile objectForKey:#"LocationArray"];
}
if(mdictPlist) {
if(self.myLocationArrayInPlist == nil){
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
}
[_myLocationArrayInPlist addObject:mdictPlist];
[savedProfile setObject:_myLocationArrayInPlist forKey:#"LocationArray"];
}
if (![savedProfile writeToFile:fullPath atomically:FALSE]) {
BFLog(#"Couldn't save LocationArray.plist savedProfile :- %# \n Location Data :- %# \n fullPath:-%#",savedProfile,mdictPlist,fullPath);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:#""];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
NSLog(#"%#",[NSString stringWithFormat:#"%#/%#", directory, file]);
if([file isEqualToString:#"LocationArray.plist"]){
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#/%#", directory, file] error:&error];
if (!success || error) {
// it failed.
BFLog(#"Delete error : %#",error);
}
else {
[self saveLocationsToPlist:myLocationDictInPlist];
}
}
}
}
}
Any idea about this issue.
I'm receiving a String from a web service and I would like to store it as a pdf file.
I know the have asked before but the answer is always the same. I've tryed it and didn't worked, and it's not explained enough.
So, this is what I'm doing:
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [#"documents/" stringByAppendingPathComponent:formattedName];
NSError *error = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error]) {
}
It's not entering in the if, and I think the file is not being generated.
I'm working with objective-c, xcode 9.
What should I modify?
Create it
NSError*error=nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"/Application Support"];
NSString*filePathC = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"historyImages"]];
if(![[NSFileManager defaultManager]fileExistsAtPath:filePathC])
{
if(
[[NSFileManager defaultManager] createDirectoryAtPath:filePathC
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"created");
}
else
{
NSLog(#"not created");
}
}
else
{
NSLog(#"exists");
}
///
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [filePathC stringByAppendingPathComponent:formattedName];
NSError *error2 = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error2]) {
}
im seeking for assistant.In my case i have file such as
RN150622103444544_pr.pdf
RN150622103444544_ID_GD.pdf
RN150622103444544_CA.xml
My question is how can i delete all the file only by referring the RN150622103444544.
Currently my code is deleting one by one.
Below are my sample code
-(void)deleteOldPdfs:(NSString *)proposal
{
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_pr_1.pdf",proposal]]])
{
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_pr_1.pdf",proposal]] error:&error];
}
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_id_GD.pdf", proposal]]]){
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_id_GD.pdf", proposal]] error:&error];
}
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_CA.xml", proposal]]]){
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_CA.xml",proposal]] error:&error];
}
}
Thank in advance
You could put the unique suffixes in an array and then loop over the array.
Sample code (untested):
NSArray *suffixList = #[#"pr_1.pdf", #"id_GD.pdf", #"CA.xml"];
NSError *error = nil;
NSFileManager *fm = [NSFileManager defaultManager];
for (NSString *suffix in suffixList) {
NSString *path = [FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_%#",proposal, suffix]];
if([fm fileExistsAtPath:path]){
[fm removeItemAtPath:path error:&error];
}
}
Note: paths and docmentsDirectory were not used in the question code and are not included in the answer.
I want to create a file in my application document folder and i have to store some content. That content takes from my localhost file. So i write a below code. But this code didn't create a file in my application document folder.
- (void) createFile
{
NSString *strPath = [NSString stringWithFormat:#"http://192.168.5.117/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"File Exists");
}
else
{
NSLog(#"File not exists");
}
NSString *content = [NSString stringWithFormat:#"%#",data];
[content writeToFile:strLastpath atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
}
While build for running i got this.
2013-10-11 11:36:38.833 SampleFileCreation[1321:c07] Path : http://192.168.5.117/~mac/banana.obj
File Name : Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] Database Path : /Users/mac/Library/Application Support/iPhone Simulator/6.1/Applications/4FA749DF-D12D-4956-AF76-140D2F981F17/Documents/Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] File not exists
You can also try this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *fileName = #"yourFileName";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/fileName"];
NSDate *data = [NSData dataWithContentsOfURL:YourUrl]; // get date form url
[data writeToFile:dataPath atomically:YES]; // save data in file
I found the answer. File created successfully.
- (void) createFile {
NSString *strPath = [NSString stringWithFormat:#"http://-.-.-.-/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
docsDir=[docsDir stringByAppendingString:#"/Object File"];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSError *theError = nil;
NSFileManager *filemgr = [NSFileManager defaultManager];
**//I added this line**
[filemgr createDirectoryAtPath:docsDir
withIntermediateDirectories:YES
attributes:nil
error:&theError];
**//Changed this line**
[data writeToFile:[docsDir stringByAppendingPathComponent:strLastpath]
options:NSDataWritingAtomic
error:&theError];
if ([filemgr fileExistsAtPath:[docsDir stringByAppendingPathComponent:strLastpath]]){
NSLog(#"File Exists");
} else {
NSLog(#"File not exists");
NSLog(#"Tell Me error %#",[theError localizedDescription]);
}
}
Is it actually possible to call NSKeyedArchiver archiveRootObject and work with data protection API setting the file attribute to NSFileProtectionComplete or NSFileProtectionCompleteUnlessOpen ?
First attempt to write the object to the specific location, in this case docFile (this is set to the documents directory). Then apply the file attributes to the docFile.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString* docFile = [docDir stringByAppendingPathComponent: #"Somefile.plist"];
NSError* error;
if([NSKeyedArchiver archiveRootObject:tempData toFile:docFile]) {
NSDictionary *fileAttributes = [NSDictionary
dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
if([[NSFileManager defaultManager] setAttributes:fileAttributes
ofItemAtPath:docFile error: &error]) {
NSLog(#"Success");
}
else {
NSLog#(%#", error);
}
}