THIS CONTENT DOWNLOAD SHORTLY

Objective

This tutorial describes how to work with iOS file system in detail. Here we will go through all the basic concepts of file management with both files and directories and how to handle it from iPhone application.

 

Example demo describes all key concepts like read/write file/directory, create file/directory, remove file/directory, access all permission of file/directory etc.

 

Step 1 Swift Method

Here we will start by short introduction of NSFileManager class, which allows you to perform generic file system operations. These file operations can be performed using shared file manager object.

Few useful methods of NSFileManager describes as per following:

+ (NSFileManager *)defaultManager: This method returns object of shared file manager for the file system.
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error  This method searches for specified directory and returns the path of items in directory. If any error occurs then access error information by setting error objects. You can also specify nil as parameter if you don’t want error information.
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *) contents attributes:(NSDictionary *)attributes This method creates a file with given content and attributes at given location.
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error This method removes directory or file at specified path.
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *) dstPath error:(NSError **)error This method copies file or directory from its source path to its destination path (new location).
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *) dstPath error:(NSError **)error This method moves file or directory from its source path to its destination path (new location).
- (BOOL)fileExistsAtPath:(NSString *)path This method returns a Boolean value which indicates that weather file or directory is exists at specified path or not.

Following are code snippet of various methods, which performs various functions of file management.

First of all we have to declare following member variable in viewController class.

 

Step 2 Create file at specific path

@IBAction func btnCreateFileClicked(sender: AnyObject)
{
filePath=documentDir?.stringByAppendingPathComponent("file1.txt")
fileManagaer?.createFileAtPath(filePath, contents: nil, attributes: nil)
 
      filePath=documentDir?.stringByAppendingPathComponent("file2.txt")
      fileManagaer?.createFileAtPath(filePath, contents: nil, attributes: nil)
self.showSuccessAlert("Success", messageAlert: "File created successfully")
}

For showSuccessAlert method.

Its body provided by following:

func showSuccessAlert(titleAlert:NSString,messageAlert:NSString)
{
        var alert:UIAlertController=UIAlertController(title:titleAlert, message: messageAlert, preferredStyle: UIAlertControllerStyle.Alert)
        var okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default)
        {
                UIAlertAction in
        }
        alert.addAction(okAction)
        if UIDevice.currentDevice().userInterfaceIdiom == .Phone
        {
            self.presentViewController(alert, animated: true, completion: nil)
        }
}
 

Step 3 Create directory at specific path

@IBAction func btnCreateDirectoryClicked(sender: AnyObject)
{
filePath=documentDir?.stringByAppendingPathComponent("/folder1")
fileManagaer?.createDirectoryAtPath(filePath, withIntermediateDirectories: false, attributes: nil, error: nil)
      self.showSuccessAlert("Success", messageAlert: "Directory created successfully")
}
 

Step 4 Check file content equality

@IBAction func btnEqualityClicked(sender: AnyObject)
{
        var filePath1=documentDir?.stringByAppendingPathComponent("temp.txt")
        var filePath2=documentDir?.stringByAppendingPathComponent("copy.txt")
 
        if(fileManagaer? .contentsEqualAtPath(filePath1, andPath: filePath2))
        {
            self.showSuccessAlert("Message", messageAlert: "Files are equal.")
        }
        else
        {
            self.showSuccessAlert("Message", messageAlert: "Files are not equal.")
        }
}
 

Step 5 Write File

@IBAction func btnWriteFileClicked(sender: AnyObject)
{
var content:NSString=NSString(string: "helllo how are you?")
var fileContent:NSData=content.dataUsingEncoding(NSUTF8StringEncoding)
        fileContent .writeToFile(documentDir?.stringByAppendingPathComponent("file1.txt"), atomically: true)
        self.showSuccessAlert("Success", messageAlert: "Content written successfully")
}
 

Step 6 Read File

@IBAction func btnReadFileClicked(sender: AnyObject)
{
        filePath=documentDir?.stringByAppendingPathComponent("/new/file1.txt")
        var fileContent:NSData?
        fileContent=fileManagaer?.contentsAtPath(filePath)
        var str:NSString=NSString(data: fileContent, encoding: NSUTF8StringEncoding)
        self.showSuccessAlert("Success", messageAlert: "data : \(str)")
}
 

Step 7 Copy File

@IBAction func btnCopyFileClicked(sender: AnyObject)
{
        filePath=documentDir?.stringByAppendingPathComponent("temp.txt")
        var originalFile=documentDir?.stringByAppendingPathComponent("temp.txt")
        var copyFile=documentDir?.stringByAppendingPathComponent("copy.txt")
        fileManagaer?.copyItemAtPath(originalFile, toPath: copyFile, error: nil)
        self.showSuccessAlert("Success", messageAlert:"File copied successfully")
}
 

Step 8 Move File

@IBAction func btnMoveClicked(sender: AnyObject)
{
        var oldFilePath:String=documentDir!.stringByAppendingPathComponent("/folder1/move.txt") as String
        var newFilePath:String=documentDir!.stringByAppendingPathComponent("temp.txt") as String
        var err :NSError?
        fileManagaer?.moveItemAtPath(oldFilePath, toPath: newFilePath, error:&err)
        if(err)
        {
            println("errorrr \(err)")
        }
        self.showSuccessAlert("Success", messageAlert: "File moved successfully")
}
 

Step 9 File Permissions

@IBAction func btnFilePermissionClicked(sender: AnyObject)
    {
        filePath=documentDir?.stringByAppendingPathComponent("temp.txt")
        var filePermissions:NSString = ""
 
        if(fileManagaer?.isWritableFileAtPath(filePath))
        {
            filePermissions=filePermissions.stringByAppendingString("file is writable. ")
        }
        if(fileManagaer?.isReadableFileAtPath(filePath))
        {
            filePermissions=filePermissions.stringByAppendingString("file is readable. ")
        }
        if(fileManagaer?.isExecutableFileAtPath(filePath))
        {
            filePermissions=filePermissions.stringByAppendingString("file is executable.")
        }
        self.showSuccessAlert("Success", messageAlert: "\(filePermissions)")
    }
 

Step 10 Directory Contents

@IBAction func btnDirectoryContentsClicked(sender: AnyObject)
    {
        var arrDirContent=fileManagaer?.contentsOfDirectoryAtPath(documentDir, error: nil)
        self.showSuccessAlert("Success", messageAlert: "Content of directory \(arrDirContent)")
    }
 

Step 11 Remove File

@IBAction func btnRemoveFile(sender: AnyObject)
    {
        filePath=documentDir?.stringByAppendingPathComponent("temp.txt")
        fileManagaer?.removeItemAtPath(filePath, error: nil)
        self.showSuccessAlert("Message", messageAlert: "File removed successfully.")
    }
 

Step 12 iOS Simulator Screen Shot

ios simulator screen shot file management

I hope you found this blog helpful while working with iOS File Management using Swift. Let me know if you have any questions or concerns regarding iOS, please put a comment here and we will get back to you ASAP.

Got an Idea of iPhone App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best iPhone App Development Company in India.

I am iOS developer, as a developer my basic goal is continue to learn and improve my development skills , to make application more user friendly.