Working with Files in Swift on iOS 17

In the chapter entitled Working with Directories in Swift on iOS 17, we looked at the FileManager, FileHandle, and Data Foundation Framework classes. We discussed how the FileManager class enables us to work with directories when developing iOS-based apps. We also spent some time covering the file system structure used by iOS. In particular, we looked at the temporary and Documents directories assigned to each app and how the location of those directories can be identified from within the app code.

In this chapter, we move from working with directories to covering the details of working with files within the iOS SDK. Once we have covered file-handling topics in this chapter, the next chapter will work through an app example that puts theory into practice.

Obtaining a FileManager Instance Reference

Before proceeding, first, we need to recap the steps necessary to obtain a reference to the app’s FileManager instance. As discussed in the previous chapter, the FileManager class contains a property named default that is used to obtain a reference. For example:

let filemgr = FileManager.defaultCode language: JavaScript (javascript)

Once a reference to the file manager object has been obtained, it can be used to perform some basic file-handling tasks.

Checking for the Existence of a File

The FileManager class contains an instance method named fileExists(atPath:), which checks whether a specified file already exists. The method takes as an argument an NSString object containing the path to the file in question and returns a Boolean value indicating the presence or otherwise of the specified file:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

let filemgr = FileManager.default

if filemgr.fileExists(atPath: "/Applications") {
    print("File exists")
} else {
    print("File not found")
}Code language: PHP (php)

Comparing the Contents of Two Files

The contents of two files may be compared for equality using the contentsEqual(atPath:) method. This method takes as arguments the paths to the two files to be compared and returns a Boolean result to indicate whether the file contents match:

let filePath1 = docsDir + "/myfile1.txt"
let filePath2 = docsDir + "/myfile2.txt"

if filemgr.contentsEqual(atPath: filePath1, andPath: filePath2) {
    print("File contents match")
} else {
    print("File contents do not match")
}Code language: JavaScript (javascript)

Checking if a File is Readable/Writable/Executable/Deletable

Most operating systems provide some level of file access control. These typically take the form of attributes designed to control the level of access to a file for each user or user group. As such, it is not certain that your program will have read or write access to a particular file or the appropriate permissions to delete or rename it. The quickest way to find out if your program has a particular access permission is to use the isReadableFile(atPath:), isWritableFile(atPath:), isExecutableFile(atPath:) and isDeletableFile(atPath:) methods. Each method takes a single argument in the form of the path to the file to be checked and returns a Boolean result. For example, the following code excerpt checks to find out if a file is writable:

if filemgr.isWritableFile(atPath: filePath1) {
    print("File is writable")
} else {
    print("File is read-only")
}Code language: PHP (php)

To check for other access permissions, substitute the corresponding method name in place of isWritableFile(atPath:) in the above example.

Moving/Renaming a File

A file may be renamed (assuming adequate permissions) using the moveItem(atPath:) method. This method takes as arguments the pathname for the file to be moved and the destination path. If the destination file path already exists, this operation will fail:

do {
    try filemgr.moveItem(atPath: filePath1, toPath: filePath2)
    print("Move successful")
} catch let error {
    print("Error: \(error.localizedDescription)")
}Code language: PHP (php)

Copying a File

File copying can be achieved using the copyItem(atPath:) method. As with the move method, this takes as arguments the source and destination pathnames:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

do {
    try filemgr.copyItem(atPath: filePath1, toPath: filePath2)
    print("Copy successful")
} catch let error {
    print("Error: \(error.localizedDescription)")
}Code language: PHP (php)

Removing a File

The removeItem(atPath:) method removes the specified file from the file system. The method takes as an argument the pathname of the file to be removed:

do {
    try filemgr.removeItem(atPath: filePath2)
    print("Removal successful")
} catch let error {
    print("Error: \(error.localizedDescription)")
}Code language: PHP (php)

Creating a Symbolic Link

A symbolic link to a particular file may be created using the createSymbolicLink(atPath:) method. This takes as arguments the path of the symbolic link and the path to the file to which the link is to refer:

do {
    try filemgr.createSymbolicLink(atPath: filePath2, 
            withDestinationPath: filePath1)
    print("Link successful")
} catch let error {
    print("Error: \(error.localizedDescription)")
}Code language: PHP (php)

Reading and Writing Files with FileManager

The FileManager class includes some basic file reading and writing capabilities. These capabilities are somewhat limited compared to the options provided by the FileHandle class but can be useful nonetheless.

First, the contents of a file may be read and stored in a Data object through the use of the contents(atPath:) method:

let databuffer = filemgr.contents(atPath: filePath1)Code language: JavaScript (javascript)

Having stored the contents of a file in a Data object, that data may subsequently be written out to a new file using the createFile(atPath:) method:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

filemgr.createFile(atPath: filePath2, contents: databuffer, 
				attributes: nil)Code language: CSS (css)

In the above example, we have essentially copied the contents from an existing file to a new file. This, however, gives us no control over how much data is to be read or written and does not allow us to append data to the end of an existing file. Furthermore, if the file in the above example had already existed, any data it contained would have been overwritten by the source file’s contents. Clearly, some more flexible mechanism is required. The Foundation Framework provides this in the form of the FileHandle class.

Working with Files using the FileHandle Class

The FileHandle class provides a range of methods designed to provide a more advanced mechanism for working with files. In addition to files, this class can also be used for working with devices and network sockets. In the following sections, we will look at some of the more common uses for this class.

Creating a FileHandle Object

A FileHandle object can be created when opening a file for reading, writing, or updating (in other words, both reading and writing). Having opened a file, it must subsequently be closed when we have finished working with it using the closeFile method. If an attempt to open a file fails, for example, because an attempt is made to open a non-existent file for reading, these methods return nil.

For example, the following code excerpt opens a file for reading and then closes it without actually doing anything to the file:

let file: FileHandle? = FileHandle(forReadingAtPath: filePath1)

    if file == nil {
        print("File open failed")
    } else {
        file?.closeFile()
}Code language: JavaScript (javascript)

FileHandle File Offsets and Seeking

FileHandle objects maintain a pointer to the current position in a file. This is referred to as the offset. When a file is first opened, the offset is set to 0 (the beginning of the file). This means that any read or write operations performed using the FileHandle instance methods will take place at offset 0 in the file. Therefore, it is first necessary to seek the required offset to perform operations at different locations in a file (for example, append data to the end of the file). For example, to move the current offset to the end of the file, use the seekToEndOfFile method.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Alternatively, seek(toFileOffset:) allows you to specify the precise location in the file to which the offset is to be positioned. Finally, the current offset may be identified using the offsetInFile method. The offset is stored as an unsigned 64-bit integer to accommodate large files.

The following example opens a file for reading and then performs several method calls to move the offset to different positions, outputting the current offset after each move:

let file: FileHandle? = FileHandle(forReadingAtPath: filePath1)

if file == nil {
    print("File open failed")
} else {
    print("Offset = \(file?.offsetInFile ?? 0)")
    file?.seekToEndOfFile()
    print("Offset = \(file?.offsetInFile ?? 0)")
    file?.seek(toFileOffset: 30)
    print("Offset = \(file?.offsetInFile ?? 0)")
    file?.closeFile()
}Code language: PHP (php)

File offsets are a key aspect of working with files using the FileHandle class, so it is worth taking extra time to ensure you understand the concept. Without knowing where the current offset is in a file, it is impossible to know the location in the file where data will be read or written.

Reading Data from a File

Once a file has been opened and assigned a file handle, the contents of that file may be read from the current offset position. The readData(ofLength:) method reads a specified number of bytes of data from the file starting at the current offset. For example, the following code reads 5 bytes of data from offset 10 in a file. The data read is returned encapsulated in a Data object:

let file: FileHandle? = FileHandle(forReadingAtPath: filepath1)

if file == nil {
    print("File open failed")
} else {
    file?.seek(toFileOffset: 10)
    let databuffer = file?.readData(ofLength: 5)
    file?.closeFile()
}Code language: JavaScript (javascript)

Alternatively, the readDataToEndOfFile method will read all the data in the file, starting at the current offset and ending at the end of the file.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Writing Data to a File

The write method writes the data contained in a Data object to the file starting at the location of the offset. Note that this does not insert data but overwrites any existing data in the file at the corresponding location.

To see this in action, let’s assume the existence of a file named quickfox.txt containing the following text:

The quick brown fox jumped over the lazy dogCode language: plaintext (plaintext)

Next, we will write code that opens the file for updating, seeks to position 10, and then writes some data at that location:

let file: FileHandle? = FileHandle(forUpdatingAtPath: filePath1)

if file == nil {
    print("File open failed")
} else {
    if let data = ("black cat" as
        NSString).data(using: String.Encoding.utf8.rawValue) {
        file?.seek(toFileOffset: 10)
        file?.write(data)
        file?.closeFile()
    }
}Code language: JavaScript (javascript)

When the above program is compiled and executed, the contents of the quickfox.txt file will have changed to:

The quick black cat jumped over the lazy dogCode language: plaintext (plaintext)

Truncating a File

A file may be truncated at the specified offset using the truncateFile(atOffset:) method. To delete the entire contents of a file, specify an offset of 0 when calling this method:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

let file: FileHandle? = FileHandle(forUpdatingAtPath: filePath1)

if file == nil {
    print("File open failed")
} else {
    file?.truncateFile(atOffset: 0)
    file?.closeFile()
}Code language: JavaScript (javascript)

Summary

Like other operating systems, iOS provides a file system to store user and app files and data locally. In this and the preceding chapter, file, and directory handling have been covered in some detail. The next chapter, entitled iOS 17 Directory Handling and File I/O in Swift – A Worked Example, will work through the creation of an example explicitly designed to demonstrate iOS file and directory handling.


Categories