Implement writing and reading to Property List (.plist) in Swift

Data writing and data reading to Property List (.plist file) is performed using a model compliant with PropertyListEncoder (Decoder) and Codable.

Premise

Swift: 5.0

Implementation

Preparing the model

Create a model of the data you want to save in the Property List in a form that conforms to Codable. This time, as an example, let's use Book, which has a title and author name as elements, as a model.

Book.swift


struct Book: Codable {
    var title: String
    var writerName: String
}

Writing data

File operations are performed using FileManager. You can write to the Property List by encoding the model prepared earlier using PropertyListEncoder.

BookManager.swift


class BookManager {
    //URL Path of the Property List to be handled
    static private var plistURL: URL {
        let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return documents.appendingPathComponent("book.plist")
    }

    static func write(book: Book) {
        let encoder = PropertyListEncoder()
        //Encode the data you want to save
        guard let data = try? encoder.encode(book) else { return }
        //Overwrite if the Property List already exists. If not, create a new one
        if FileManager.default.fileExists(atPath: plistURL.path) {
            try? data.write(to: plistURL)
        } else {
            FileManager.default.createFile(atPath: plistURL.path, contents: data, attributes: nil)
        }
    }
}

Data reading

Similar to writing data, file operations are performed using FileManager. The data read from the Property List is decoded into the Book model using PropertyListDecoder.

BookManager.swift


class BookManager {
    //abridgement//

    static func load() -> Book {
        let decoder = PropertyListDecoder()
        //Read data from the destination Property List and decode
        guard let data = try? Data.init(contentsOf: plistURL), 
              let book = try? decoder.decode(Book.self, from: data) else { 
              return Book(title: "", writerName: "")
        }
        return book
    }
}

At the end

By using Codable andPropertyListEncoder (Decoder), I was able to easily implement data manipulation with Property List (.plist).

reference

Recommended Posts

Implement writing and reading to Property List (.plist) in Swift
Reading and writing gzip files in Java
Property reading in POJO
How to implement UICollectionView in Swift with code only
I tried to chew C # (reading and writing files)
How to implement infinite scrolling (page nate) in Swift TableView
Implement Swift UITextField in code
Try to implement Yubaba in Java
[Swift] Property observers willSet and didSet
How to bind request parameters in list format with bean property in Spring
(For super beginners) Getter / setter and property to think in D language
Shorten the UUID to base64 in Swift.
How to implement search functionality in Rails
How to implement date calculation in Java
How to implement Kalman filter in Java
Try to implement n-ary addition in Java
[Swift] How to fix Label in UIPickerView
[Java] Reading and writing files with OpenCSV
Change List <Optional <T >> to Optional <List <T >> in Java
[Swift] How to implement the countdown function
How to implement coding conventions in Java
[Swift] Implement tap and long press processing!
[Swift5] How to implement standby screen using'PKHUD'
How to implement ranking functionality in Rails
Arrylist and linked list difference in java
[Swift5] How to implement animation using "lottie-ios"
How to implement asynchronous processing in Outsystems
How to overwrite Firebase data in Swift
Java to C and C to Java in Android Studio
Swift beginners tried to implement microwave logic!
Hex and UIColor mutual conversion in Swift
How to fix a crash when deleting Realm data in Swift UI List