Filemanager in swift & iOS , Storing data in .plist files

Hey hope ya’ll are doing great , Here we are gonna discuss about using the FileManager instance in swift so that you can store data in files and use it for your upcoming projects . Filemanager is very handy and its api’s are super easy to understand and use as well . Filemanager allows you to store data of your app in files you can create , delete , update and read those you have full control over it 😉.
Here i am gonna show you some basic functionality to get you started with FileManager. You can store you files and folders in document directory of your device , to get started you have to first create a Filemanager instance Filemanager.default
, default is the shared instance of Filemanager and that’s what we are gonna use,
let manager = FileManager.default
Our first step will be to navigate to document directory and you can do that by
guard let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first else {return}
urls
Returns an array of URLs for the specified common directory in the requested domains. In easy language it returns a array with different urls and the first element in the array is the url for document directory and that’s what we are interested in
You can print the path by printing url.path
and use command open “ThePrintedPathHere”
in your terminal to open the directory in your finder
Now that we have the right directory (Remember you can do anything in this directory), We are gonna create a folder let fileUrl = url.appendingPathComponent(“Folder”)
try? manager.createDirectory(at: fileUrl, withIntermediateDirectories: true, attributes: nil)
This will create a folder named “Folder” at specified path of FileUrl (You can print FileUrl.path too and open it as well) if you want another folder inside the folder You can do it easily by just appending one more path in the FileUrl
example
let fileUrl = url.appendingPathComponent(“Folder”).appendingPathComponent(“Second-Folder”)
You can create a full hierarchy as you want ,
Lets Delete this directory , Nothing too fancy you can easily do it try? FileManager.default.removeItem(atPath: fileUrl.path)
this will Delete the folder at specified path
Creating File ,
Same way you can also create any file that you want whether its a text file of .plist file etc
let fileUrl = url.appendingPathComponent(“file.txt”)let data = “Hey this is File content”.data(using: .utf8)try! manager.createFile(atPath: fileUrl.path, contents: data, attributes: nil)
Here we pass the path and contents for that txt file , the data is string which is than converted into type Data using the .utf8 encoding ,If you want to pass any extra metadata related to folder or file you can pass it in attributes of create method or just keep it nil as default,
You can also delete file using try! manager.removeItem(atPath: fileUrl.path)
Now lets get Towards creating .plist files
what are plist Files? , they are actually xml files used to store data in form of key and values pair (sort of like dictionaries in swift) , you can also find one in your Xcode project called info.plist , they are plist files
Create a plist file as shown below
let fileUrl = url.appendingPathComponent(“file.plist”)try! manager.createFile(atPath: fileUrl.path, contents: nil, attributes: nil)
Also create our data to store in file , we will have a struct and store an array of that struct types , make sure the struct confirms to Codable protocol
struct User:Codable {let firstName:Stringlet lastName:String}
var users = [User(firstName: “James”, lastName: “Smith”),User(firstName: “Maria”, lastName: “Garcia”)]
Now we are gonna store that users
array in plist , for that we need to encode out data using the property list encoder and same way while retrieving the data we are gonna decode the data using property list decoder , Codable is typealias for Encodable and Decodable protocol .
Storing our data ,
let encoder = PropertyListEncoder()let encodedData = try! encoder.encode(users)try! encodedData.write(to: fileUrl)
This encoder.encode
will encode and return data we than write the data to our file , Note: Here i am using try! this is not a good practice if you are gonna use this code for a production project ,do proper error handling using do{} catch{}
blocks to convey errors
Retrieving Data from plist ,
let data = try! Data(contentsOf: fileUrl)let decoder = PropertyListDecoder()let arr = try! decoder.decode([User].self, from: data)print(arr)
here we retrieve the data and print it , remember the data we stored was of type [User] so we pass the data type and data as arguments , that’s it there are more of other methods too, Be sure to check the apple’s developer documents here
Note:If you try to decode an empty .plist file than it will throw an error , Also if you create a file with filename that already exist’s in the same directory than the new File will replace the existing One Also replacing the data in it
So this is it for now , I Hope you guys enjoyed it 😀 Be sure to like and share it , Also Check out my Twitter and Github , Follow me on medium to get more of these , Thank you.