Basic file operations in iOS

Hello friends… 🙂 This time I was able to come comparatively earlier with a new blog post related to iOS mobile application development. Today I am going to show you, how to do basic file operations such as, check a file availability, create, read and delete a file in iOS. 

You know that I’m more prone to present coding but not the UI. So here comes the dull UI of the application that we are going to create today 😉

Figure One

Figure 1

As you can see from the Figure 1, there are three buttons at the bottom which will execute our three major tasks as described in the UIButton label. Before operate each function, it will check whether the same file is already created or not, which covers the remaining task I have mentioned in the paraphrase.

Okay… first thing first. Where are you going to create the file and how you manually check whether the file is actually created or not? Don’t worry, I’m going to walk you through those steps. There are several places you can create a file such as in Documents directory, Library or Temporary directory. In this tutorial you are going to create your file in Documents directory of the application. Following is the way, how you get the path of the application’s Documents directory.

 * Getting the Application Documents file path
 * @return NSString - Absolute path of the Documents directory
- (NSString *)documentsDirectoryPath {
 if (debugEnable) NSLog(@"%@ * documentsDirectoryPath", TAG);
 * Creates a list of directory search paths
 * NSDocumentDirectory = searching for Documents directory
 * NSUserDomainMask = inside user's home directory
 * YES = Expandind tilde into it's real path
 NSArray *directoryPathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// if (debugEnable) NSLog(@"%@ # directoryPathsArray = %@", TAG, directoryPathsArray);
 NSString *documentsDirectory = [directoryPathsArray objectAtIndex:0];
// if (debugEnable) NSLog(@"%@ # documentsDirectory = %@", TAG, documentsDirectory);
 return documentsDirectory;

Let comments and NSLog explains the code to you and I’m moving to our first operation, which is checking file availability. I like to emphasis you on one thing which I haven’t done in my code, that is, do your all file operation tasks in a separate thread but not in the main thread. I’m repeating, I haven’t done it this source code because I don’t want to complex the post, but I have used NSThread in my previous post, therefor you are not so naive to use that now 🙂  Below is the way you check file availability using code.

 * Check existency of a given file
 * \param relativeFilePath Relative path of the file
 * @return BOOL whether file exists or not
- (BOOL)checkFileInPath:(NSString *)relativeFilePath {
 if (debugEnable) NSLog(@"%@ * checkFileInPath", TAG);
 NSString *absoluteFilePath = [NSString stringWithFormat:@"%@/%@", [self documentsDirectoryPath], relativeFilePath];
BOOL fileExistency = [[NSFileManager defaultManager] fileExistsAtPath:absoluteFilePath];
 return fileExistency;

You will be provided all relevant source code at the end of this post. These operations are in ANUFileOperations.m file. Codes were written according to MVC pattern, so you can understand it without a hassle. If the file that we are going to create is not in the path, you can see the updated UI as below.

Figure Two

Figure 2

If there is no file, you are going to create one. This is how you gonna do it.

 * Create a file with the given name inside given directory
 * \param relativePath Directories hirarchy that file should create
 * \param fileName Name of the creating file
 * @return BOOL Successibility of file creation
- (BOOL)createFileinPath:(NSString *)relativePath withName:(NSString *)fileName {
 if (debugEnable) NSLog(@"%@ * createFile: name", TAG);
NSString *creatingDirPath = [NSString stringWithFormat:@"%@/%@/", [self documentsDirectoryPath], relativePath];
 * Create directory in the given path
 * If there are subdirectories mentioned in given path, create those too
 * The creating directory gets default attributes
 [[NSFileManager defaultManager] createDirectoryAtPath:creatingDirPath withIntermediateDirectories:YES attributes:nil error:nil];
 NSError *errorWritingFile;
 NSString *fileContent = @"Never give up";
 NSString *absFilePath = [NSString stringWithFormat:@"%@%@", creatingDirPath, fileName];
 // Write the content to the file in the given path using given encoding system
 BOOL fileCreateSuccessibility = [fileContent writeToFile:absFilePath atomically:YES encoding:NSUTF8StringEncoding error:&errorWritingFile];
 return fileCreateSuccessibility;

When the file created successfully, your application UI will update too.

Figure Three

Figure 3

Now file has been created. Can you see it? Why can’t 🙂 But you have to learn something new. What you going to learn is see your application files using iTunes on your PC. Follow these steps;

  • Select your project in Xcode Navigator
  • Then select the target under TARGETS option which will appear after you do above step
  • Then select info tab
  • Expand Custom iOS Target Properties
  • Add a new key Application supports iTunes file sharing with the type Boolean and value YES

That’s it. Next time you run the application using a real device which is connected to your MAC, you can see your application appear in Apps tab inside Device selection. Then you can copy it to your local directory and open using TextEditor application to see the file content.

For the simulator users, the file is located on your PC and you can see the path when you uncomment the NSLog I have used in documentsDirectoryPath method.

What if you need to read the file content programatically. This is how you gonna do it.

 * Read the file content in the given path
 * \param relativeFilePath FIle path relative to Documents directory
 * @return NSString File content as string value
- (NSString *)readFileInPath:(NSString *)relativeFilePath {
 if (debugEnable) NSLog(@"%@ * readFileInPath", TAG);
 NSString *absoluteFilePath = [NSString stringWithFormat:@"%@/%@", [self documentsDirectoryPath], relativeFilePath];
 NSError *readingError;
 NSString *fileContent = [NSString stringWithContentsOfFile:absoluteFilePath encoding:NSUTF8StringEncoding error:&readingError];
return fileContent;

In our simple application you can see the content of the file populate in the view as below.

Figure Four

Figure 4

With that we are going to learn our last task for this blog post. That is, you are going to delete the file you have created above.

 * Delete file in the given path
 * \param relativeFilePath FIle path relative to Documents directory
 * @return BOOL Whether file deleted or not
- (BOOL)deleteFileInPath:(NSString *)relativeFilePath {
 if (debugEnable) NSLog(@"%@ * deleteFileInPath", TAG);
 NSString *absoluteFilePath = [NSString stringWithFormat:@"%@/%@", [self documentsDirectoryPath], relativeFilePath];
 // If the given path is a directory, the contents of the will be removed recursively
 BOOL isFileDeleted = [[NSFileManager defaultManager] removeItemAtPath:absoluteFilePath error:nil];
 return isFileDeleted;
Figure Five

Figure 5

Those are the basic operations that I’m going to cover with this post. Hope you have learned something. As I promised this is the link to Github to download the relevant source code for this post. Seems there is some unusual code formatting happening with this post. Thousands apologies for that.

See you guys with a new post. Wish I can continue this iOS blog posting without any interruption. Have fun 🙂

About AnujAroshA

Working as an Associate Technical Lead. Specialized in iOS application development. A simple person :)
This entry was posted in iOS and tagged , , . Bookmark the permalink.

5 Responses to Basic file operations in iOS

  1. Mohammed Fairoz says:

    can u please explain this by using the example that the beginners who have just stated ios can catch this highly coded example.

  2. Mohammed Fairoz says:

    Can u give a simple example of create,insert,delete and how to store the database using sqlite in iOS it will be helpful for me because iam trying to do that but not understanding how to come up with this problem.

  3. Mohammed Fairoz says:

    reply these answers as soon as possible please….

  4. yogesh says:

    tell me what are app constants.h ?where do i get this file?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s