Copy a file to the Documents directory in iOS

This is a simple method that I use to copy a file from the app bundle to the Documents directory. You can’t modify files in the app bundle, but you can modify them if they are in the Documents directory.


- (void)createResultsDocument {
    
    NSString *documentsDirectory = [self applicationDocumentsDirectory];
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"HTML_header.html"];
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *todaysDate = [dateFormatter stringFromDate:[NSDate date]];
    NSString *resultsFileName = [NSString stringWithFormat:@"MPResults_%@.html",todaysDate];
    NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:resultsFileName];
    NSError *error;
    
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath 
                                            toPath:destinationPath
                                             error:&error];
    NSLog(@"The copy error is: %@", error);
    
    // Check that it worked.
    NSURL *resultsURL = [NSURL fileURLWithPath:destinationPath];
    NSLog(@"The resultsURL is: %@", resultsURL);
}

Xcode Buttons

This is some code I used to put a reset button on the screen. It’s mostly self-documenting. First, create a rect. I’ve already defined the x and y coordinates—buttonX and distanceFromTop based on the screen width and other buttons on the screen. Likewise, I’ve already defined the width. The rest of the code is just assigning properties to the button. The action is a method in the file that changes the image to a ‘Selected’ image.


// Reset Button
    @synthesize resetButton = resetButton;
    ....

    CGRect resetButtonFrame = CGRectMake(buttonX, distanceFromTop,
                                         button_width, 25.0f);            
    self.resetButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.resetButton.titleLabel.font            = [UIFont systemFontOfSize: 16];
    self.resetButton.titleLabel.textColor       = [UIColor blueColor];
    self.resetButton.titleLabel.shadowOffset    = CGSizeMake (1.0, 0.0);
    [self.resetButton setTitle:@"Reset Scoring" forState:UIControlStateNormal];
    [self.resetButton setFrame:resetButtonFrame];
    [self.resetButton addTarget:self 
                             action:@selector(resetScorekeeper:) 
                   forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.resetButton];
    // This line makes the icons stay in the center of the screen when you rotate
    self.resetButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    
    ....

- (IBAction)resetScorekeeper:(UIButton *)sender {
    
    [self resetResultsFile];
    [sender setImage:[UIImage imageNamed:@"ResetScoringSelected.png"] forState:UIControlStateNormal];
}

Making MySQL do what you want.

Just some miscellaneous code that I’ve been using to update fields in my database. Basically lots of trimming and concatenating. A little substring manipulating thrown in for good measure.


SELECT *  FROM `words_for_slps` WHERE `F` REGEXP 'z$' AND `pronunciation` REGEXP 'z$'

UPDATE`words_for_slps` SET `phonemes` = TRIM(TRAILING 's' FROM phonemes) WHERE `F` REGEXP 'z$' AND `phonemes` REGEXP 's$' AND `word` = 'Ares'

UPDATE`words_for_slps` SET `phonemes` = CONCAT(phonemes,'z') WHERE `F` REGEXP 'z$' AND `pronunciation` REGEXP 'z$'

UPDATE`words_for_slps` SET `phonemes` = TRIM(TRAILING 's hz' FROM phonemes) WHERE `F` REGEXP 'hz$' AND `phonemes` REGEXP 'hz$'

UPDATE`words_for_slps` SET `phonemes` = CONCAT(phonemes,'ʃ ɛ z') WHERE `F` REGEXP 'z$'

UPDATE`words_for_slps` SET `phonemes` = CONCAT(phonemes,'z') WHERE `F` REGEXP 'z$' AND `pronunciation` REGEXP 'z$'
UPDATE`words_for_slps` SET `phonemes` = CONCAT(phonemes,' ɛ s') WHERE `F` REGEXP 's' AND `phonemes` REGEXP 'n$'

UPDATE `words_for_slps` SET `phonemes` = TRIM(LEADING 'c' FROM phonemes) WHERE `word` REGEXP '^c' AND `I` LIKE 'c'
UPDATE `words_for_slps` SET `phonemes` = CONCAT('k',phonemes) WHERE `phonemes` REGEXP '^ ' AND `I` LIKE 'c'

UPDATE `words_for_slps` SET `phonemes` = TRIM(LEADING 'k' FROM phonemes) WHERE `word` REGEXP '^cy' AND `phonemes` REGEXP '^k'
UPDATE `words_for_slps` SET `phonemes` = CONCAT('s',phonemes) WHERE `word` REGEXP '^cy' AND `phonemes` REGEXP '^ '

UPDATE `words_for_slps` SET `phonemes` = REPLACE(phonemes, 't ɛ,i  d', 't ə d') WHERE `phonemes` REGEXP 't ɛ,i  d$' AND `pronunciation` REGEXP 't u d$'

UPDATE `words_for_slps` SET `phonemes` = REPLACE(phonemes, 'n z', 'nz') WHERE `pronunciation` REGEXP 'n z$' AND `phonemes`REGEXP 'n z$'

I used these select statements to look for words that need some manual cleanup.


SELECT *  FROM `words_for_slps` WHERE `F` <> SUBSTRING_INDEX(phonemes, ' ', -1)
SELECT *  FROM `words_for_slps` WHERE `word` REGEXP '^w' AND `pronunciation` NOT REGEXP '^w' AND `pronunciation` IS NOT NULL

This works when I want to update the fields in one table with values from fields in another table.


UPDATE words_for_slps, words_for_slpsBAK12
SET words_for_slps.grade = words_for_slpsBAK12.grade
WHERE words_for_slps.word_id = words_for_slpsBAK12.word_id;

Even though I’m only updating one table you’d think this should work, but it doesn’t.


UPDATE `words_for_slps` 
LEFT JOIN `words_for_slpsBAK12` ON `words_for_slps.word_id` = `words_for_slpsBAK12.word_id`
SET `words_for_slps.grade` = `words_for_slpsBAK12.grade`

Finding Directories in iOS

I created a Utilities singleton to keep things I refer to often. These are the methods I use for referring to directories.


#pragma mark - Application's Documents directory
// Directory locations
+ (NSString *)applicationCachesDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}

+ (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

+ (NSString *)applicationLibraryDirectory {
    
    return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
}

Here’s one for retrieving the contents of a file stored in the Caches Directory. Notice how it uses [self applicationCachesDirectory] to get the location of the directory.


// Cached files for results
+ (NSString *)cachedFilePath:(NSString *)fileName {
    NSString *pathComponent = [NSString stringWithFormat:@"%@.txt",fileName];
    NSString *filePath = [[self applicationCachesDirectory] stringByAppendingPathComponent:pathComponent];
    return filePath;
}

If I want to store the results in the Documents directory, I’ll use this to construct the path.


        NSString *resultsFilePath = [ [Utilities applicationDocumentsDirectory] stringByAppendingPathComponent:[self formattedHTMLFileName:@"Results"] ];

Here’s a slightly more complicated example where I retrieve the contents of a cached file. Note that it makes use of cachedFilePath:fileName as described above.


+ (NSString *)cachedFileContents:(NSString *)fileName {
    NSStringEncoding encoding; NSError* error = nil;
    NSString *text = [NSString stringWithContentsOfFile:[self cachedFilePath:fileName] usedEncoding:&encoding error:&error];
    return text;
}

Here’s another example. This time I’m loading a string with the contents of the FullResults file.


 NSStringEncoding encoding;
    NSError* error = nil;
    NSString *resultsText = [NSString stringWithContentsOfFile:[Utilities cachedFilePath:@"FullResults"] usedEncoding:&encoding error:&error];

Rename a bunch of files

Photoshop mangles file names when you run batch saves on them, so I’ve had to rename a bunch of files after processing. Here’s what I do from the shell prompt to rename a bunch of files in a PictsFolder.

Create a file called rename.sh


#!/bin/bash
cd /Users/gmiller/Desktop/PictsFolder
mv 1.png a.png
mv 2.png b.png
exit

chmod it to be executable. I use chmod 777 rename.sh because I’m lazy. Then run it from the command line.

jscarry$ /Users/gmiller/Files/renamePicts.sh
Be sure to escape special characters like spaces in your file names.

e.g. File\ Name\ With\ Spaces.png