From 872a1b403e5332daffc58f7b3123dc3782f4f07e Mon Sep 17 00:00:00 2001 From: zyphs21 Date: Sun, 11 Aug 2019 15:36:53 +0800 Subject: [PATCH 1/2] add encode function for Plist --- Sources/InfoKit/Plist.swift | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Sources/InfoKit/Plist.swift b/Sources/InfoKit/Plist.swift index f04ac4e..bd227a8 100644 --- a/Sources/InfoKit/Plist.swift +++ b/Sources/InfoKit/Plist.swift @@ -77,6 +77,35 @@ public class Plist { } + /// Encode the data into plist file + /// + /// - Parameter data: class to encode + /// - Returns: whether encode and write to tht plist file success + public func encode(data: T) -> Bool { + guard let resource = self.resource else { + return false + } + + guard let path = self.bundle.path(forResource: resource, ofType: "plist", inDirectory: nil) else { + #if DEBUG + print("Resource: \(resource) not found in bundle: \(self.bundle)") + #endif + return false + } + + do { + let encoder = PropertyListEncoder() + let data = try encoder.encode(data) + try data.write(to: URL(fileURLWithPath: path)) + return true + } catch { + #if DEBUG + print("Error Encoding \(error)") + #endif + return false + } + } + /// Returns the value associated with the default bundled Info.plist file. /// /// - Parameter plist: The Plist provider From 7c6c0d399cb1bce5e6f6e40e50355cd0c6649d1e Mon Sep 17 00:00:00 2001 From: zyphs21 Date: Sun, 11 Aug 2019 15:40:42 +0800 Subject: [PATCH 2/2] add test case for encode function --- Tests/PlistTests.swift | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Tests/PlistTests.swift b/Tests/PlistTests.swift index 8158dc2..b2a67c3 100644 --- a/Tests/PlistTests.swift +++ b/Tests/PlistTests.swift @@ -71,4 +71,24 @@ class PlistTests: XCTestCase { } + func testEncodeUserProvidedPlist() { + + // Mocks + struct Products: Codable { + let foo: String + let bar: String + } + + // Given + let bundle = Bundle(for: PlistTests.self) + let plist = Plist("Products", in: bundle) + + let newProduct = Products(foo: "new foo", bar: "new foo bar") + + let result = plist.encode(data: newProduct) + + XCTAssertEqual(result, true) + + } + }