iOS File Management System
In iOS we can perform multiple operations on file system like create new file in directory, write content to file, read content from file, remove file from directory, move file from one directory to another directory, etc.
Now we will see how to perform all these operations in iOS file system in swift with example.
Create iOS File Management App in Swift
To create new project in iOS open Xcode from /Applications folder directory. Once we open Xcode the welcome window will open like as shown below. In welcome window click on the second option “Create a new Xcode Project” or choose File à New à Project.
After selecting “Create a new Xcode project” a new window will open in that we need to choose template.
The new Xcode window will contain several built-in app templates to implement common type of iOS apps like page based apps, tab-based apps, games, table-view apps, etc. These templates are having pre-configured interface and source code files.
For this iOS File Management example, we will use most basic template “Single View Application”. To select this one, Go to the iOS section in left side à select Application à In main area of dialog select “Single View Application” and then click on next button like as shown below.
After click Next we will get window like as shown below, in this we need to mention project name and other details for our application.
Product Name: “File Management in iOS”
The name whatever we enter in Product Name section will be used for the project and app.
Organization Name: “Tutlane”
You can enter the name of your organization or your own name or you can leave it as blank.
Organization Identifier: “com.developersociety”
Enter your organization identifier in case if you don't have any organization identifier enter com.example.
Bundle Identifier: This value will generate automatically based on the values we entered in Product Name and Organization Identifier.
Language: “Swift”
Select language type as “Swift” because we are going to develop applications using swift.
Devices: “Universal”
Choose Devices options as Universal it means that one application is for all apple devices in case if you have any specific requirement to run app only for iPad then you can choose the iPad option to make your application restricted to run only on iPad devices.
Use Core Data: Unselected
This option is used for database operations. In case if you have any database related operations in your application select this option otherwise unselect the option.
Include Unit Tests: Unselected
In case if you need unit tests for your application then select this option otherwise unselect it.
Include UI Tests: Unselected
In case if you need UI tests for your application then select this option otherwise unselect it.
Once you finished entering all the options then click on Next button like as shown below.
Once we click on Next button new dialog will open in that we need to select the location to save our project. Once you select the location to save project then click on Create button like as shown below
After click on Create button the Xcode will create and open a new project. In our project Main.storyboard and ViewController.swift are the main files which we used to design app user interface and to maintain source code.
Main.storyboard - Its visual interface editor and we will use this file to design our app user interface
ViewController.swift - It contains source code of our application and we use this file to write any code related to our app.
Now in project select Main.storyboard file the Xcode will open visual interface editor like as shown below.
Now select ViewController.swift file in your project that view will be like as shown below.
Add iOS UI Controls to View in Swift
Now we will add controls to our application for that open Object Library. The Object Library will appear at the bottom of Xcode in right side. In case if you don't find Object library, click on the button which is at the third position from the left in the library selector bar like as shown below. (Alternatively you can choose View à Utilities à Show Object Library.)
As we discussed our user interface will be in Main.storyboard file so open Main.storyboard file. Now in Object library search for Table View in Filter field then drag and drop Table View into Main.storyboard ViewController like as shown below.
Now click on ViewController à Go to the Editor à Embed In à Navigation Controller. Now we will see that there are two controllers in our storyboard file.
Once we done all the settings we need to write custom code in ViewController.swift file to create new file / directory, write text to file, read text from file, remove file from directory, etc like as shown below
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var actionTable: UITableView!
var numberArray = NSMutableArray()
var fileManager:NSFileManager?
var documentDir:NSString?
var filePath:NSString?
override func viewDidLoad() {
super.viewDidLoad()
numberArray.addObject("Create File")
numberArray.addObject("Create Directory")
numberArray.addObject("Write File")
numberArray.addObject("Read File")
numberArray.addObject("Move File")
numberArray.addObject("Copy File")
numberArray.addObject("Directory Contains")
numberArray.addObject("Remove File")
numberArray.addObject("File Permissions")
fileManager=NSFileManager .defaultManager()
let dirPaths:NSArray=NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDir=dirPaths[0] as? NSString
print("path : \(documentDir)")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = actionTable.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = numberArray.objectAtIndex(indexPath.row) as? String
cell.selectionStyle=UITableViewCellSelectionStyle.None
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
returnnumberArray.count;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if indexPath.row==0
{
filePath=documentDir?.stringByAppendingPathComponent("file1.txt")
filePath=documentDir?.stringByAppendingPathComponent("file1.txt")
fileManager?.createFileAtPath(filePath! as String, contents: nil, attributes: nil)
self.sucessAlert("Success",alertMessage:"File created successfully")
}
else if indexPath.row==1
{
filePath=documentDir?.stringByAppendingPathComponent("/folder1")
do {
try fileManager?.createDirectoryAtPath(filePath! as String, withIntermediateDirectories: false, attributes: nil)
} catch_ {
}
self.sucessAlert("Success", alertMessage: "Directory created successfully")
}
elseif indexPath.row==2
{
let content:NSString=NSString(string: "File Manager in iOS Using Swift")
let fileContent:NSData=content.dataUsingEncoding(NSUTF8StringEncoding)!
fileContent .writeToFile(documentDir!.stringByAppendingPathComponent("file1.txt"), atomically: true)
self.sucessAlert("Success", alertMessage: "Content written successfully")
}
else if indexPath.row==3
{
filePath=documentDir?.stringByAppendingPathComponent("/file1.txt")
var fileContent:NSData?
fileContent=fileManager?.contentsAtPath(filePath! asString)
let str:NSString=NSString(data: fileContent!, encoding: NSUTF8StringEncoding)!
self.sucessAlert("Success", alertMessage: "data : \(str)")
}
else if indexPath.row==4
{
let oldFilePath:String=documentDir!.stringByAppendingPathComponent("file1.txt") as String
let newFilePath:String=documentDir!.stringByAppendingPathComponent("/folder1/file1.txt") as String
var err :NSError?
do {
try fileManager?.moveItemAtPath(oldFilePath, toPath: newFilePath)
} catch let error as NSError {
err = error
}
if((err) != nil)
{
print("errorrr \(err)")
}
self.sucessAlert("Success", alertMessage: "File moved successfully")
}
else if indexPath.row==5
{
let originalFile=documentDir?.stringByAppendingPathComponent("file1.txt")
let copyFile=documentDir?.stringByAppendingPathComponent("copy.txt")
do {
try fileManager?.copyItemAtPath(originalFile!, toPath: copyFile!)
} catch_ {
}
self.sucessAlert("Success", alertMessage:"File copied successfully")
}
else if indexPath.row==6
{
var error: NSError? = nil
var arrDirContent: [AnyObject]?
do {
arrDirContent = tryfileManager!.contentsOfDirectoryAtPath(documentDir as! String)
} catch let error1 as NSError {
error = error1
arrDirContent = nil
}
self.sucessAlert("Success", alertMessage: "Content of directory \(arrDirContent)")
}
else if indexPath.row==7
{
filePath=documentDir?.stringByAppendingPathComponent("file1.txt")
do {
try fileManager?.removeItemAtPath(filePath as! String)
} catch_ {
}
self.sucessAlert("Message", alertMessage: "File removed successfully.")
}
else if indexPath.row==8
{
filePath=documentDir?.stringByAppendingPathComponent("file1.txt")
var filePermissions:NSString = ""
if((fileManager?.isWritableFileAtPath(filePath! as String)) != nil)
{
filePermissions=filePermissions.stringByAppendingString("file is writable. ")
}
if((fileManager?.isReadableFileAtPath(filePath! as String)) != nil)
{
filePermissions=filePermissions.stringByAppendingString("file is readable. ")
}
if((fileManager?.isExecutableFileAtPath(filePath! as String)) != nil)
{
filePermissions=filePermissions.stringByAppendingString("file is executable.")
}
self.sucessAlert("Success", alertMessage: "\(filePermissions)")
}
}
/////////////////SUCESS ALERT /////////////////////////////
func sucessAlert(titleAlert:NSString,alertMessage:NSString)
{
let alert:UIAlertController=UIAlertController(title:titleAlert as String, message: alertMessage as String, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default)
{
UIAlertAction in
}
alert.addAction(okAction)
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
Now we will run and check the output of application. To run application, select the required simulator (Here we selected iPhone 6s Plus) and click on Play button, located at the top-left corner of the Xcode toolbar like as shown below.
Output of iOS File Management App in Swift
Now when you run the application you see the result now click on “Create File” the file will create in directory with text “File Manager in iOS Using Swift” and it will show the alert “File Created Successfully”.
If you want to know where the file is created click on Xcode Editor at bottom you can able to see the directory path just copy that directory like as shown below
Now click on “Finder” à select “Go to Folder” and paste the following directory and click on “Go” button like as shown below
Now you see that file1.txt created in default directory like as shown below.
Now we need permission to write or read content from the “file1.txt” file for that click on “File Permissions” button like as shown below.
Now click on “Read File” to get the data from newly created file. If you observe we created file with text “File Manager in iOS Using Swift” that will appear in our alert box.
This is how we can access file system in iOS applications to create new file, read file, write file, move file to another folder, etc. based on our requirements.
No comments:
Post a Comment