Question

Using the code below is the only way I can get writeToFile to actually save a file. It outputs to this directory:

/Users/Eric/Library/Containers/net.ericmann.Event-Gadget-Workshop-App/Data/Documents/gadget.ics

- (IBAction)Saved:(id)sender { 
    [self writeToTextFile];
    //mySaved.stringValue = [NSString stringWithFormat:@"Saved!"];
}


-(void) writeToTextFile{
    //get the documents directory:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    //NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];


    //NSString *pathToDesktop = [NSString stringWithFormat:@"/Users/%@/Desktop", NSUserName()];


    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/gadget.ics", documentsDirectory];

    //create content - four lines of text
    NSString *content = myOutput.stringValue;

    //save content to the documents directory
    [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
    mySaved.stringValue = fileName;
    myTestBox.stringValue = fileName;
}

Now, if I use the code below, nothing will write. I have the test file name output, and it's pointing here:

/Users/Eric/Desktop/gadget.ics

-(void) writeToTextFile{
    //get the documents directory:

    // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);

    //NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    //NSString *documentsDirectory = [paths objectAtIndex:0];


    NSString *pathToDesktop = [NSString stringWithFormat:@"/Users/%@/Desktop", NSUserName()];

    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/gadget.ics", pathToDesktop];

    //create content - four lines of text
    NSString *content = myOutput.stringValue;

    //save content to the documents directory
    [content writeToFile:fileName atomically:NO  encoding:NSStringEncodingConversionAllowLossy error:nil];
    mySaved.stringValue = fileName;
    myTestBox.stringValue = fileName;
Was it helpful?

Solution

You will likely end up figuring out a solution if you actually make use of the error parameter there in the "writeToFile" method:

e.g.:

NSError * error = NULL;
BOOL success = [content writeToFile:fileName atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(success == NO)
{
    NSLog( @"error saving to %@ - %@", fileName, [error localizedDescription] );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top