Pages

Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

September 27, 2013

Remove the extension from a file

A convenient and easy to remember function for removing the file extension.


/** Returns only the name of a file without its extension.

 It's only a shortcut for `[[ NSString lastPathComponent] stringByDeletingPathExtension]`.

 @param str Name of the file (or even the full path).
 @return Returns the file name without extension.

 */
+ (NSString *)removeExtensionFromFile:(NSString *)str {
    return [[str lastPathComponent] stringByDeletingPathExtension];
}



Download the ready-for-use source file (.m) of Remove the extension from a file

September 22, 2013

Save raw data to a local file

How can I save NSData to a persistent local file in iOS SDK?
The answer is pretty simple: use this helpful Objective-C method.
You need:
- http://objective-c-functions.blogspot.com/2013/07/create-directory-in-ios-file-system.html


/** Saves data to device filesystem and returns its path.

 @param data Data to save.
 @param fileName String representing the name of the file in which data get stored.
 @param localFolder Full path of folder that contains the file.
 @return Returns file path of saved data.

 */
+ (NSString *)saveData:(NSData *)data toLocalFile:(NSString *)fileName inFolder:(NSString *)localFolder {
    // If folder does not exist then it will be created on the fly.
    BOOL isDir;
    BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:localFolder isDirectory:&isDir];
    if (!exists || !isDir) {
        [LMFunctions createFolderWithName:localFolder];
    }

    // Save the file.
    NSString *filePath = [localFolder stringByAppendingPathComponent:fileName];
    [data writeToFile:filePath atomically:YES];
    return filePath;
}



Download the ready-for-use source file (.m) of Save raw data to a local file

September 19, 2013

Write and Append text to file

Sometimes you need to write to an already existing file, that is append text to file.
Here's an example.


/** Append text to a file located in the /Documents directory.

 If file does not exist it will be created from scratch.

 @param str String to write.
 @param fileName Name of the file.

 */
+ (void)writeAndAppendString:(NSString *)str toFile:(NSString *)fileName {

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if (0 < [paths count]) {
        NSString *documentsDirPath = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirPath stringByAppendingPathComponent:fileName];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            // Add the text at the end of the file.
            NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
            [fileHandler seekToEndOfFile];
            [fileHandler writeData:data];
            [fileHandler closeFile];
        } else {
            // Create the file and write text to it.
            [data writeToFile:filePath atomically:YES];
        }
    }
}



Download the ready-for-use source file (.m) of Write and Append text to file

September 3, 2013

Empty a directory in your iOS App

How to empty a folder in Objective-C ?
A must have method! I always use it to erase my log files.


/** Empty a folder contents.

 @param folder Full path of the folder to be emptied.
 @return Returns true on success, false otherwise.

 */
+ (BOOL)emptyFolder:(NSString *)folder {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err;
    NSArray *tmpFiles = [fileManager contentsOfDirectoryAtPath:folder error:&err];
    if (err) {
        LogError(@"Error occured: %@", err);
        return NO;
    }
    for (NSString *file in tmpFiles) {
        [fileManager removeItemAtPath:[folder stringByAppendingPathComponent:file] error:&err];
        if (err) {
            LogError(@"Error occured: %@", err);
            return NO;
        }
    }
    return YES;
}



Download the ready-for-use source file (.m) of Empty a directory in your iOS App

August 25, 2013

Delete not allowed chars for filesystem

I often save files from my iPhone app to a Windows PC. While under iOS you might use some characters, in a Windows system you can't.
So I built this Objective-C function to help me manage the not-safe chars.


/** Trim all character that are not allowed or not safe on Windows filesystem.

 This function keeps only "a-z", "A-Z", "0-9", "space", "-" and "_" characters.
 It also deletes empty spaces at the beginning and end of the name.
 In addition, no dots are allowed at the end of the name.

 @param str Original string.
 @return Returns a Windows-safe string.

 */
+ (NSString *)trimCharactersNotAllowedOnWindowsFileSystemFromString:(NSString *)str {

    // This will turn, for example, é (U+00E9) into e’ (U+0065 U+0301).
    str = [str decomposedStringWithCanonicalMapping];

    NSMutableString *stripped = [NSMutableString stringWithCapacity:str.length];
    for (NSInteger i=0; i<str.length; i++) {
        unichar c = [str characterAtIndex:i];

        // Only allow a-z, A-Z, 0-9, space, -, _
        if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ' ' || c == '-' || c == '_' ) {
            [stripped appendFormat:@"%c", c];
        }
    }

    // No empty spaces at the beginning or end of the path name (also no dots at the end).
    return [stripped stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}



Download the ready-for-use source file (.m) of Delete not allowed chars for filesystem

August 19, 2013

Get XML data from file

XML files are used widely around in the programming environment, so with this useful function you can open a file and get its XML representation.


/** Opens a XML file and returns a XML object.

 Based on GDataXML ( http://code.google.com/p/gdata-objectivec-client ).

 @param filePath String representing full path of the file to open.
 @return Returns a GDataXMLDocument initialized with XML data taken from XML file, or nil in case of error.

 */
+ (GDataXMLDocument *)openXmlAtPath:(NSString *)filePath {
    NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
    NSError *err;
    GDataXMLDocument *obj = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&err];
    if (obj == nil) {
        return nil;
    }
    return obj;
}



Download the ready-for-use source file (.m) of Get XML data from file

August 3, 2013

Create a folder in App Temp directory

A helpful method for creating a folder in the "tmp" directory of your iOS device (iPhone, iPad, iPod).
You need:
- http://objective-c-functions.blogspot.com/2013/07/create-directory-in-ios-file-system.html


/** Creates a folder in the /tmp directory.

 @param folderNameOrPath String representing the folder name, optionally with its path (full or relative).
 @return Returns true if success, false otherwise.
 @see createFolderInDocumentDirectoryWithName:
 @see createFolderWithName:
 @see documentsDirectory

 */
+ (BOOL)createFolderInTempDirectoryWithName:(NSString *)folderNameOrPath {
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:folderNameOrPath];
    return [LMFunctions createFolderWithName:path];
}



Download the ready-for-use source file (.m) of Create a folder in App Temp directory

August 2, 2013

Create a folder in App Documents directory

A helpful method for creating a folder in the "Documents" directory of your iOS device (iPhone, iPad, iPod).
You need:
- http://objective-c-functions.blogspot.com/2013/07/get-documents-directory-of-your-app.html
- http://objective-c-functions.blogspot.com/2013/07/create-directory-in-ios-file-system.html


/** Creates a folder in the /Documents directory.

 @param folderNameOrPath String representing the folder name, optionally with its path (full or relative).
 @return Returns true if success, false otherwise.
 @see createFolderInTempDirectoryWithName:
 @see createFolderWithName:
 @see documentsDirectory

 */
+ (BOOL)createFolderInDocumentDirectoryWithName:(NSString *)folderNameOrPath {
    NSString *path = [[LMFunctions documentsDirectory] stringByAppendingPathComponent:folderNameOrPath];
    return [LMFunctions createFolderWithName:path];
}



Download the ready-for-use source file (.m) of Create a folder in App Documents directory

July 26, 2013

Create directory in iOS file system

How to create a folder in the local iOS file system?
This is an Objective-C function that deals with NSFileManager class of the Cocoa framework.


/** Creates a folder in the filesystem.

 @param folderNameOrPath String representing the folder name, optionally with its path (full or relative).
 @return Returns true if success, false otherwise.
 @see createFolderInDocumentDirectoryWithName:
 @see createFolderInTempDirectoryWithName:
 @see documentsDirectory

 */
+ (BOOL)createFolderWithName:(NSString *)folderNameOrPath {

    if (![[NSFileManager defaultManager] fileExistsAtPath:folderNameOrPath]) {
        NSError *err = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:folderNameOrPath withIntermediateDirectories:YES attributes:nil error:&err];
        if (err != nil) {
            LogError(@"Error creating the folder '%@'", folderNameOrPath);
            return NO;
        }
    }
    return YES;
}



Download the ready-for-use source file (.m) of Create directory in iOS file system

July 21, 2013

Get the Documents directory of your App

Get the "Documents" folder of your iPhone, iPad or iPod app.


/** Returns the full path of /Documents directory.

 It actually expands tilde (~) and returns the entire long path.

 @return Returns the path of /Documents directory, or nil in case of error.
 @see createFolderInDocumentDirectoryWithName:
 @see createFolderInTempDirectoryWithName:
 @see createFolderWithName:

 */
+ (NSString *)documentsDirectory {
    NSArray *paths    = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir= ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return docDir;
}



Download the ready-for-use source file (.m) of Get the Documents directory of your App